简体   繁体   English

使用C API PyRun_String时发生Python SystemError

[英]Python SystemError when using the C API PyRun_String

I am trying to run, in a C++ program, some python file that is actually included in the C++ code as a std::string called command . 我正在尝试在C ++程序中运行一些python文件,该文件实际上作为名为commandstd::string包含在C ++代码中。

I have been successful using PyRun_SimpleString(command.c_str()) , but this prevents getting exception information. 我已经成功使用PyRun_SimpleString(command.c_str()) ,但是这阻止了获取异常信息。

I now try the following instead: 我现在尝试以下方法:

PyObject* result = PyRun_String(command.c_str(), Py_file_input, PyEval_GetGlobals(), PyEval_GetLocals());

However, this throws: 但是,这引发:

SystemError: frame does not exist

What am I doing wrong? 我究竟做错了什么?

UPDATE: 更新:

I tried to split the process into compile+eval using the following: 我尝试使用以下方法将进程拆分为compile + eval:

PyObject* code = Py_CompileString(command.c_str(), filename.c_str(), Py_file_input);
PyObject* result = PyEval_EvalCode(code, PyEval_GetGlobals(), PyEval_GetLocals());

Now, the error is different: 现在,错误有所不同:

SystemError: PyEval_EvalCodeEx: NULL globals

This is maybe more explanatory, as it says in the C API doc :: 正如C API doc中所说:

Return a dictionary of the global variables in the current execution frame, or NULL if no frame is currently executing. 返回当前执行框架中全局变量的字典,如果当前没有框架在执行,则返回NULL。

I am not sure I understand what a frame is. 我不确定我了解什么是框架。

I found a solution. 我找到了解决方案。 I probably have not understood when a frame is exectuting or not, but it turns out that just after launching the interpreter, no frames are running. 我可能还不了解何时执行某个框架,但是事实证明,在启动解释器后,没有任何框架在运行。 That's why PyEval_GetGlobals() and PyEval_GetLocals() were returning NULL and caused errors later. 这就是为什么PyEval_GetGlobals()PyEval_GetLocals()返回NULL并在以后导致错误的原因。

Instead, the namespace of the default module __main__ should be used as both globals and locals namespaces: 相反,默认模块__main__的名称空间应同时用作全局名称空间和本地名称空间:

PyObject* d = PyModule_GetDict(PyImport_AddModule("__main__"));
PyObject* result = PyRun_String(command.c_str(), Py_file_input, d, d);
Py_DECREF(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM