I am attempting to embed Python in an (ultimately multiplatform) C++ app.
It\'s important that my app contains its own Python implementation (in the same way that blend
Since this doesn't really have an answer, I will offer this for posterity. I also do not have access to a Mac, so it may be a little different for you than on Linux. Also, the required dependencies must be installed for this to work, but that is usually easy enough to figure out.
Create a working directory
mkdir ~/embeddedpython
cd ~/embeddedpython
Download the Python source
wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tgz
Create an installation directory for Python
mkdir ./installation
Extract the downloaded source files
tar xvf Python-3.6.1.tgz
Enter the newly created source directory
cd Python-3.6.1
Configure Python to install in our installation directory
./configure --prefix="/home//embeddedpython/installation"
Make and install Python
make && make install
Go back to your working directory
cd ..
Create a new PYTHONHOME directory where the library will reside
mkdir home && mkdir home/lib
Copy the Python library to our new home directory
cp -r ./installation/lib/python3.6 ./home/lib/
Create a new c++ source file (embeddedpython.cpp) with the following code taken from the python documentation, with the exception of the setenv
function call.
#include
#include
int main(int argc, char *argv[])
{
setenv("PYTHONHOME", "./home", 1);
wchar_t *program = Py_DecodeLocale(argv[0], NULL);
if (program == NULL) {
fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
exit(1);
}
Py_SetProgramName(program); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
if (Py_FinalizeEx() < 0) {
exit(120);
}
PyMem_RawFree(program);
return 0;
}
Compile and run
g++ embeddedpython.cpp -I ./installation/include/python3.6m/ ./installation/lib/libpython3.6m.a -lpthread -ldl -lutil
./a.out
> Today is Fri Apr 14 16:06:54 2017
From here on it is standard embedded python as usual. With this method, the "home" directory must be included in your deployment, and the environment variable PYTHONHOME
must be set to point to it before any python related code is executed.