我正在尝试将Pyhton3程序嵌入到C ++程序中。在阅读了几篇教程和博客文章后,我得到了以下代码,但失败了:
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 sys\n"
"print('Hello')\n"
"import options\n"
"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;
}
结果如下:
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
因此,导入sys工作但导入我自己的模块失败,而添加模块的路径似乎有效。
有什么想法吗?
答案 0 :(得分:0)
PyBytes_FromString
替换PyUnicode_DecodeFSDefault
使导入工作正常。我不明白为什么。