Embedding Python with C++
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: 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,因此不会期望有效的命令行。这就是为什么它在没有上面代码的情况下工作的原因。
- Problems with std::cin.fail()
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 这对"With a stackless coroutine, only the top-level routine may be suspended."意味着什么
- Boost.TEST with CLion: "Test framework quit unexpectedly"
- 避免碎片化的ClientHellos with OpenSSL (DTLS)
- Issues with Win32 ReadProcessMemory API
- Qt with WinAPI MouseProc
- [[maybe_unused]] with structured_binding?
- Issue with WriteProcessMemory
- OpenCV RTP-Stream with FFMPEG
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- std::adjacent_difference with std::chrono time_point
- DLL Made with CMake 使程序崩溃
- QtCreator with C 库中的链接器问题
- SHBrowseForFolder with BIF_BROWSEFORCOMPUTER and SHGetPathFr
- specialized std::default_delete with QQmlComponent
- VS2019 - Sudo Remote Debugging on Linux with Cmake project
- Inference pytorch C++ with alexnet and cv::imread image
- Pybind11: init<> with lambda
- Incomings Call with Android Sip stack in Embarcadero C++ bui