2017-10-08 143 views
0

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)

如果有人需要有關問題的更多信息,請讓我知道,我會嘗試在這裏提供。

+0

以何種方式不行? Python 3的純Python版本可以很好地適用於Python 3,所以我不明白爲什麼C-API版本不會? – DavidW

+0

我將編輯問題並放入我正在使用的代碼。 – user2540800

+0

'stdOutErr'中的縮進看起來不正確。這將是我的第一個猜測 – DavidW

回答

0

你的問題是,.value不是bytes對象,它是一個string(即Python2 unicode)對象。因此PyBytes_AsString失敗。我們可以用PyUnicode_AsEncodedString將它轉換爲bytes對象。

PyObject *output = PyObject_GetAttrString(catcher,"value"); //get the stdout and stderr from our catchOutErr 
PyObject* encoded = PyUnicode_AsEncodedString(output,"utf-8","strict"); 
printf("Here's the output:\n %s", PyBytes_AsString(encoded)); 

請注意,您應該檢查這些結果PyObject*對NULL,看看是否出現了錯誤。

+0

感謝DavidW,您的提示用上面的代碼解決了問題。我還有其他疑問,在我工作的代碼中,''PyUnicode_AsEncodedString'總是返回'NULL'。其他函數正在工作(或者至少它們不返回'NULL')。你知道它會是什麼嗎? – user2540800

+0

這意味着它引發了一個例外。你應該檢查檢查,找出發生了什麼問題。自從您重定向標準錯誤以來,這有點困難。有可能除了「嚴格」​​以外的爭論可能會使其工作。 – DavidW