Calling python from a c++ program for distribution Calling python from a c++ program for distribution python python

Calling python from a c++ program for distribution


I would like to call python script files from my c++ program.

This means that you want to embed Python in your C++ application. As mentioned in Embedding Python in Another Application:

Embedding Python is similar toextending it, but not quite. Thedifference is that when you extendPython, the main program of theapplication is still the Pythoninterpreter, while if you embedPython, the main program may havenothing to do with Python — instead,some parts of the applicationoccasionally call the Pythoninterpreter to run some Python code.

I suggest that you first go through Embedding Python in Another Application. Then refer the following examples

  1. Embedding Python in C/C++: Part I

  2. Embedding Python in C/C++: Part II

  3. Embedding Python in Multi-Threaded C/C++ Applications

If you like Boost.Python, you may visit the following links:

  1. Embedding Python with Boost.Python Part 1


Boost has a python interface library which could help you.

Boost.Python


Interestingly, nobody has mentioned pybind11, yet. From their documentation:

pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa, mainly to create Python bindings of existing C++ code. Its goals and syntax are similar to the excellent Boost.Python library by David Abrahams: to minimize boilerplate code in traditional extension modules by inferring type information using compile-time introspection. [...] Since its creation, this library has grown beyond Boost.Python in many ways, leading to dramatically simpler binding code in many common situations.

Concretely, calling into a Python function (called embedding) is as simple as this (taken from the documentation):

#include <pybind11/embed.h> // everything needed for embeddingnamespace py = pybind11;int main() {    py::scoped_interpreter guard{}; // start the interpreter and keep it alive    py::print("Hello, World!"); // use the Python API}