在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