我使用Python C++ API来运行C++程序中的Python命令。我想捕获所有python输出到一个字符串,我通过以下重定向来捕获pythons 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解释器的输出。。。。在
Python解释器将运行在C++进程中,所以它的所有输出将转到C++程序本身的STDRR和STDUT。如何捕获这个输出在this answer中描述。注意,使用这种方法,您不需要再捕获Python脚本中的输出,只要让它进入STDUT并在C++中立即捕获所有内容即可。在
相关问题 更多 >
编程相关推荐