Running an C++ exetuable with embedded python

0

I am on Windows 10, having installed WinPython 64 3.8.5 and Mingw w64. I want to call python code from C++ and started using the following example code:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

int main(int argc, char *argv[])
{
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;
}

Compilation runs through smoothly (g++ myfile.cpp -Ipath/to/Python.h -Lpath/to/python38.lib -lpython38) However, when running the exe in cmd (after running C:\Users\liebschs\Programs\WinPython64-3.8.5\WPy64-3850\scripts\env.batch in that cmd), I obtain the following error:

  Python path configuration:
  PYTHONHOME = (not set)
  PYTHONPATH = (not set)
  program name = 'embed.exe'
  isolated = 0
  environment = 1
  user site = 1
  import site = 1
  sys._base_executable = 'C:\\Users\\liebschs\\MyFiles\\playground\\VSprojects\\EmbedPython\\embed.exe'
  sys.base_prefix = 'C:\\Users\\liebschs\\Programs\\WinPython64-3.8.5\\WPy64-3850\\python-3.8.5.amd64'
  sys.base_exec_prefix = 'C:\\Users\\liebschs\\Programs\\WinPython64-3.8.5\\WPy64-3850\\python-3.8.5.amd64'
  sys.executable = 'C:\\Users\\liebschs\\MyFiles\\playground\\VSprojects\\EmbedPython\\embed.exe'
  sys.prefix = 'C:\\Users\\liebschs\\Programs\\WinPython64-3.8.5\\WPy64-3850\\python-3.8.5.amd64'
  sys.exec_prefix = 'C:\\Users\\liebschs\\Programs\\WinPython64-3.8.5\\WPy64-3850\\python-3.8.5.amd64'
  sys.path = [
    'C:\\Users\\liebschs\\Programs\\WinPython64-3.8.5\\WPy64-3850\\python-3.8.5.amd64\\python38.zip',
    '.\\DLLs',
    '.\\lib',
    'C:\\Users\\liebschs\\MyFiles\\playground\\VSprojects\\EmbedPython',
  ]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'

Current thread 0x000021c8 (most recent call first):
<no Python frame>

Any help is appreciated! Btw:

  • Running python scripts directly (i.e. doing "python helloworld.py" in cmd) or using pip does not cause an error and runs as expected.
  • switching to a virtual environment, does not change anything
python-3.8
asked on Stack Overflow Oct 26, 2020 by johnny1357 • edited Oct 27, 2020 by johnny1357

1 Answer

0

Contrary to what I read elsewhere, the problem is resolved when I set PYTHONPATH and PYTHONHOME to the python.exe, in my case C:\Users\liebschs\Programs\WinPython64-3.8.5\WPy64-3850\python-3.8.5.amd64

answered on Stack Overflow Oct 27, 2020 by johnny1357

User contributions licensed under CC BY-SA 3.0