This document demonstrates how to run pybind11 programs in Jupyter notebook in the most simple way using Xeus-Cling kernel. Sample programs here include:
- simple Hello world program
- embedded module via
PYBIND11_EMBEDDED_MODULE
macro
conda install -c conda-forge xeus-cling
conda install -c conda-forge pybind11
conda install -c conda-forge notebook
#pragma cling add_include_path("/home/jupyter/miniconda3/include/python3.9/")
#pragma cling add_library_path("/home/jupyter/miniconda3/lib")
#pragma cling load("python3.9")
#include <pybind11/embed.h>
#include <iostream>
namespace py = pybind11;
void py_print(py::object o)
{
std::cout << py::str(o).cast<std::string>() << "\n";
};
py::scoped_interpreter python;
py::str s{"Hello world"};
py_print(s);
#pragma cling add_include_path("/home/jupyter/miniconda3/include/python3.9/")
#pragma cling add_library_path("/home/jupyter/miniconda3/lib")
#pragma cling load("python3.9")
#include <pybind11/embed.h>
#include <iostream>
namespace py = pybind11;
void py_print(py::object o)
{
std::cout << py::str(o).cast<std::string>() << "\n";
};
PYBIND11_EMBEDDED_MODULE(hello, m)
{
m.def("world", []() { return "Hello world"; });
}
py::scoped_interpreter python;
py_print(py::module::import("hello").attr("world")());
- The buildin function
py::print()
prints into the terminal where you're running jupyter notebook, hence using custompy_print()
. Suggestions how to redirect output ofpy::print()
into the notebook are welcomed. - Exception handling with
catch(const py::error_already_set& e)
sometimes works, sometimes not. Suggestions how to fix that are welcomed. - The compiler seems to compile in Release mode. Enabling Debug mode would be beneficial, but how?