Embed Python in your C++ application without Python installed on guest machine

For my Piger application, I wanted my C++ app to parse Python scripts but I quickly became aware of the fact that the user must have Python installed on their machine, not only that they needed the same version as mine, (version 3.5).

The normal call would be something like…

#include <Python.h>
...
// This will cause an error if the user does not have the same version of Python as the one we want.
// or if they do not have Python installed at all.
Py_Initialize();
...

But that throws an error when the user does not have Python installed.
And if they have an older version installed, it _might_ work, but the scripts might not work as expected.

The solution is to embed the Python you want to run in your app.

  1. Go to the Python website and download the Embeddable zip file for your app, (x64 or x86)
  2. Extract the python35.zip located inside that zip file
  3. Copy it somewhere where it can be referenced.
  4. Add the code below.
#include <Python.h>
...    
std::wstring exe_dir = L"\\exe\\path";
std::wstring python_path;
python_path += exe_dir + L"python35.zip";
Py_SetPath(python_path.c_str());

// Now we can call Initialize
Py_Initialize();
...

Now your app will work using version Python 3.5.1