在old question关于如何捕捉蟒蛇的stdout在C++代码,there is a good answer和它的作品 - 但只有在Python 2如何捕捉Python 3的标准输出在C++代码
我想用类似的东西与Python 3.任何人都可以帮助我吗?
UPDATE
我使用的代码如下。它被从上面引用的Mark回答中移除,唯一的变化是使用PyBytes_AsString
而不是PyString_AsString
,因为cited in documentation。
#include <Python.h>
#include <string>
int main(int argc, char** argv)
{
std::string stdOutErr =
"import sys\n\
class CatchOutErr:\n\
def __init__(self):\n\
self.value = ''\n\
def write(self, txt):\n\
self.value += txt\n\
catchOutErr = CatchOutErr()\n\
sys.stdout = catchOutErr\n\
sys.stderr = catchOutErr\n\
"; //this is python code to redirect stdouts/stderr
Py_Initialize();
PyObject *pModule = PyImport_AddModule("__main__"); //create main module
PyRun_SimpleString(stdOutErr.c_str()); //invoke code to redirect
PyRun_SimpleString("print(1+1)"); //this is ok stdout
PyRun_SimpleString("1+a"); //this creates an error
PyObject *catcher = PyObject_GetAttrString(pModule,"catchOutErr"); //get our catchOutErr created above
PyErr_Print(); //make python print any errors
PyObject *output = PyObject_GetAttrString(catcher,"value"); //get the stdout and stderr from our catchOutErr object
printf("Here's the output:\n %s", PyBytes_AsString(output)); //it's not in our C++ portion
Py_Finalize();
return 0;
}
我建立它使用Python 3库:
g++ -I/usr/include/python3.6m -Wall -Werror -fpic code.cpp -lpython3.6m
,输出是:
Here's the output: (null)
如果有人需要有关问题的更多信息,请让我知道,我会尝试在这里提供。
以何种方式不行? Python 3的纯Python版本可以很好地适用于Python 3,所以我不明白为什么C-API版本不会? – DavidW
我将编辑问题并放入我正在使用的代码。 – user2540800
'stdOutErr'中的缩进看起来不正确。这将是我的第一个猜测 – DavidW