从C++调用的Python函数未定义
我在从C++调用一个简单的Python脚本时遇到了问题。
我有一个简单的用例来说明这个问题;
在Python脚本中,函数fb应该调用已事先定义好的fa。
然而我却得到一个错误:
调用了fb
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "<string>", line 13, in <module>
File "<string>", line 10, in fb
NameError: name 'fa' is not defined
文件test.py:
def fa() :
print('Called fa')
return 3
def fb() :
print('Called fb')
return fa() * 2
fb()
print('Finished test.py')
C++代码:
#ifdef _DEBUG
#undef _DEBUG
#include <Python.h>
#define _DEBUG
#else
#include <Python.h>
#endif
#include <string>
int main() {
// Initialize the python interpreter, setting path
const char * app_path = "C:\\Python383-x64\\";
size_t convertedChars = 0;
size_t newsize = strlen(app_path);
wchar_t* wcstring = new wchar_t[newsize];
mbstowcs_s(&convertedChars, wcstring, newsize, app_path, _TRUNCATE);
Py_SetPythonHome(wcstring);
Py_Initialize();
// Create dicts for globals and locals
PyObject* globals = PyDict_New();
PyObject* locals = PyDict_New();
// Set the builtins
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
// Evaluate python code and get the result
PyObject* string_result = PyRun_String("exec(open(\"test.py\").read())", Py_single_input, globals, locals);
// check whether the python code caused any Exception
if (PyErr_Occurred()) {
PyErr_Print(); PyErr_Clear(); return 1;
}
else {
// print the result
PyObject_Print(string_result, stdout, Py_PRINT_RAW);
}
return 0;
}
解决方案
因此,答案是在字典中添加 __main__。
#ifdef _DEBUG
#undef _DEBUG
#include <Python.h>
#define _DEBUG
#else
#include <Python.h>
#endif
#include <string>
int main() {
// Initialize the python interpreter, setting path
const char * app_path = "C:\\Python383-x64\\";
size_t convertedChars = 0;
size_t newsize = strlen(app_path);
wchar_t* wcstring = new wchar_t[newsize];
mbstowcs_s(&convertedChars, wcstring, newsize, app_path, _TRUNCATE);
Py_SetPythonHome(wcstring);
Py_Initialize();
// Create dicts for globals and locals
PyObject* main_module = PyImport_AddModule("__main__");
PyObject* locals = PyModule_GetDict(main_module);
PyObject* globals = PyModule_GetDict(main_module);
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
// Evaluate python code and get the result
PyObject* string_result = PyRun_String("exec(open(\"test.py\").read())", Py_file_input, globals, locals);
// check whether the python code caused any Exception
if (PyErr_Occurred()) {
PyErr_Print(); PyErr_Clear(); return 1;
}
return 0;
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。