2010-12-03 23 views
3

我正在使用python C++ API從C++程序運行python命令。我想抓住所有的蟒蛇輸出到字符串,我已經通過了以下重定向管理,抓蟒蛇輸出和錯誤輸出:如何重定向python解釋器的輸出,並在C++程序中的字符串中捕獲它?

#python script , redirect_python_stdout_stderr.py 
class CatchOutput: 
    def __init__(self): 
     self.value = '' 
    def write(self, txt): 
     self.value += txt 
catchOutput = CatchOutput() 
sys.stdout = catchOutput 
sys.stderr = catchOutput 

#C++ code 
PyObject *pModule = PyImport_AddModule("__main__"); 
PyRun_SimpleString("execfile('redirect_python_stdout_stderr.py')"); 

PyObject *catcher = PyObject_GetAttrString(pModule,"catchOutput"); 

PyObject *output = PyObject_GetAttrString(catcher,"value"); 
char* pythonOutput = PyString_AsString(output); 

但我不知道該怎麼也捉蟒蛇解釋什麼輸出....

+0

你讀過http://docs.python.org/extending/embedding.html? – nmichaels 2010-12-03 17:26:03

回答

4

Python解釋器將你的C++程序中運行,所以它的所有輸出將轉到C++程序本身的標準錯誤和標準輸出。如何捕獲該輸出在this answer中描述。請注意,使用這種方法,您不需要再捕獲Python腳本中的輸出 - 只需讓它轉到stdout並使用C++一次捕獲所有內容即可。

相關問題