2010-12-03 20 views
3

私はpython C++ APIを使ってPythonコマンドをC++プログラムから実行しています。私はニシキヘビのstdoutとstderr出力をキャッチするために、私は以下のリダイレクトが管理してきた文字列にすべての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

答えて

4

PythonインタプリタはC++プロセス内で実行されるため、すべての出力はC++プログラム自体のstderrとstdoutに送られます。この出力をキャプチャする方法は、this answerに記載されています。このアプローチでは、Pythonスクリプトの出力をこれ以上取得する必要はありません。単にC++でstdoutに行き、すべてを一度にキャプチャするようにしてください。

関連する問題