Problem:将 Python 嵌入 C++ 时抛出奇怪的异常。
Program:
bool embedd::execute_python(std::string location)
{
if (std::ifstream(location))
{
const char* file_location = location.c_str();
FILE* file_pointer;
// Initialize the Python interpreter
Py_Initialize();
file_pointer = _Py_fopen(file_location, "r");
// Run the Python file
PyRun_SimpleFile(file_pointer, file_location);
// Finalize the Python interpreter
Py_Finalize();
return true;
}
return false;
}
上面的代码片段应该做什么:该函数应首先检查传递的参数是否是 python 文件的有效位置。如果该文件存在,那么它应该执行 Python 文件。
我是否得到了预期的结果:是和否。
出了什么问题:
测试文件1:
print("Hello world")
Result :成功执行并获得正确的输出
测试文件2:
from tkinter import *
root = Tk()
root.mainloop()
结果:异常根 = Tk() 文件
“C:\ Users \ User \ AppData \ Local \ Programs \ Python \ Python35-32 \ Lib \ tkinter__init__.py”,
1863 行,在init基本名称 = os.path.基本名称(sys.argv[0])
AttributeError:模块“sys”没有属性“argv”
使用其他一些文件进行测试,发现每当我们导入 tkinter、uuid、os 等模块(任何)时,都会引发类似的异常。在对此进行简要挖掘时,我的 IDE 的进程监视器告诉我“未加载符号文件”,例如没有为 tk86t.dll 加载符号文件
Python版本:3.5.2
我确实提到过的链接:SO - 1 https://stackoverflow.com/questions/12230210/attributeerror-module-object-has-no-attribute-argv-when-using-python-h发现这个bug已经从Python 2.3这里修复了BUGS http://bugs.python.org/issue839151
一方面,您的测试文件 2 导入 Tk,它需要有效的命令行(例如对于 WindowsC:\>python script.py -yourarguments
)由于某些原因。另一方面,您嵌入了 python,因此没有命令行。这就是 python 抱怨的(“模块‘sys’没有属性‘argv’”)。您应该在 Py_Initialize() 之后直接创建一个假命令行,如下所示:
Py_Initialize();
wchar_t const *dummy_args[] = {L"Python", NULL}; // const is needed because literals must not be modified
wchar_t const **argv = dummy_args;
int argc = sizeof(dummy_args)/sizeof(dummy_args[0])-1;
PySys_SetArgv(argc, const_cast<wchar_t **>(argv)); // const_cast allowed, because PySys_SetArgv doesn't change argv
您的测试文件 1 不导入 Tk,因此不需要有效的命令行。这就是为什么它无需上面的代码即可工作的原因。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)