簡體   English   中英

用C ++嵌入Python

[英]Embedding Python with C++

問題:使用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:\\ 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

一方面,由於某些原因,您的測試文件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,因此不會期望使用有效的命令行。 這就是為什么沒有上面的代碼就可以工作的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM