Skip to content

Jupyter Notebook running pybind11 program

Notifications You must be signed in to change notification settings

pavelschon/pybind11-notebook

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 

Repository files navigation

Jupyter Notebook running pybind11 program

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

Setup

conda install -c conda-forge xeus-cling
conda install -c conda-forge pybind11
conda install -c conda-forge notebook

Simple program

pybind11

The code

#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);

Embedded module

embed

The code

#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")());

Remarks

  • The buildin function py::print() prints into the terminal where you're running jupyter notebook, hence using custom py_print(). Suggestions how to redirect output of py::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?

Links