I’m trying to embed a Pyhton3 program into a C++ one. After following several tutorials and blog posts I get the following code, which fails:
Py_SetProgramName(_program_name); Py_Initialize(); PyObject* main = PyImport_AddModule("__main__"); PyObject* globalDictionary = PyModule_GetDict(main); PyObject* localDictionary = PyDict_New(); //create the dictionaries as shown above PyObject* pythonpath = PySys_GetObject("path"); if (PyList_Append(pythonpath, PyBytes_FromString("/path/to/my/modules")) == -1) { std::cerr << "Failed to append to python path" << std::endl; PyErr_Print(); } const char* pythonScript = "" "import sysn" "print('Hello')n" "import optionsn" "print('World')n" ""; PyObject* returnValue = PyRun_String(pythonScript, Py_file_input, globalDictionary, localDictionary); if (!returnValue) { std::cerr << "python raised an exception" << std::endl; PyErr_Print(); return 1; }
The result is the following:
Hello python raised an exception Traceback (most recent call last): File "<string>", line 5, in <module> File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2222, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 2164, in _find_spec File "<frozen importlib._bootstrap>", line 1940, in find_spec File "<frozen importlib._bootstrap>", line 1914, in _get_spec File "<frozen importlib._bootstrap>", line 2049, in find_spec File "<frozen importlib._bootstrap>", line 53, in _path_join File "<frozen importlib._bootstrap>", line 53, in <listcomp> TypeError: 'str' does not support the buffer interface
So, importing sys works but importing my own module fails, while adding the path to my modules seemed to work.
Any idea ?
Advertisement
Answer
Replacing PyBytes_FromString
by PyUnicode_DecodeFSDefault
made the import work. I don’t understand why though.