Embedding Python with C++

Embedding Python with C++

本文关键字:C++ with Python Embedding      更新时间:2023-10-16

问题:与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()

结果:异常root = tk()文件 " c: user user appdata local program python python35-32 lib tkinter__init __. py", 第1863行,in init basename = os.path.basename(sys.argv [0]) attributeError:模块'sys'没有属性'argv'

使用其他一些文件测试,发现当我们导入诸如TKINTER,UUID,OS等类似异常之类的模块时。简要介绍一下我的IDE的过程监视器告诉"未加载符号文件"

Python版本:3.5.2

我确实提到的链接:因此-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,因此不会期望有效的命令行。这就是为什么它在没有上面代码的情况下工作的原因。