gpt4 book ai didi

python - 使用 C++ 嵌入 Python

转载 作者:搜寻专家 更新时间:2023-10-31 01:32:48 25 4
gpt4 key购买 nike

问题:在使用 C++ 嵌入 Python 时抛出奇怪的异常。

程序:

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")

结果:成功执行并得到正确的输出

测试文件2:

from tkinter import *
root = Tk()
root.mainloop()

Result : Exception root = Tk() File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\Lib\tkinter__init__.py", line 1863, in init baseName = os.path.basename(sys.argv[0]) AttributeError: module 'sys' has no attribute 'argv'

测试了一些其他文件,发现无论何时我们导入模块(任何),如 tkinter、uuid、os 等,都会抛出类似的异常。在对此进行简要挖掘时,我的 IDE 的进程监视器告诉“未加载符号文件”,例如没有为 tk86t.dll 加载符号文件

Python 版本:3.5.2

我确实提到的链接: SO - 1发现该错误已从 Python 2.3 此处修复BUGS

最佳答案

一方面,出于某些原因,您的测试文件 2 导入了需要有效命令行的 Tk(例如,对于 Windows C:\>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,因此不需要有效的命令行。这就是它在没有上面的代码的情况下工作的原因。

关于python - 使用 C++ 嵌入 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42537291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com