【问题标题】:Embedding Python with C++用 C++ 嵌入 Python
【发布时间】:2017-03-01 16:42:08
【问题描述】:

问题:用 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;
}

上面的代码sn-p应该做什么:函数首先要检查传入的参数是否是python文件的有效位置。如果文件存在,那么它应该执行 Python 文件。

我是否得到了预期的结果:是和否。

出了什么问题:

测试文件1:

print("Hello world")

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

测试文件2:

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

结果:异常根 = Tk() 文件 "C:\Users\User\AppData\Local\Programs\Python\Python35-32\Lib\tkinter__init__.py", 第 1863 行,在 init baseName = os.path.basename(sys.argv[0]) AttributeError: 模块 'sys' 没有属性 'argv'

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

Python 版本:3.5.2

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

【问题讨论】:

    标签: python c++ python-3.x


    【解决方案1】:

    一方面,由于某些原因,您的测试文件 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,因此不需要有效的命令行。这就是为什么它可以在没有上面的代码的情况下工作的原因。

    【讨论】:

    • 感谢您的帮助!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2020-12-23
    • 1970-01-01
    • 2020-12-12
    相关资源
    最近更新 更多