3

私はpython C++ APIを使用して、C++プログラムからpythonコマンドを実行しています。すべてのpython出力を文字列にキャッチしたいのですが、pythonのstdoutおよびstderr出力をキャッチするために、次のリダイレクトで管理しました。

#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);

しかし、pythonsインタープリターの出力もキャッチするために何をすべきかわかりません....

4

1 に答える 1

4

Python インタープリターは C++ プロセス内で実行されるため、その出力はすべて C++ プログラム自体の stderr および stdout に送られます。この出力をキャプチャする方法は、この回答で説明されています。このアプローチでは、Python スクリプトで出力をキャプチャする必要がなくなることに注意してください。標準出力に出力して、C++ ですべてを一度にキャプチャするだけです。

于 2010-12-03T17:29:38.557 に答える