【问题标题】:How to redirect python interpreter output and catch it in a string in C++ program?如何重定向 python 解释器输出并将其捕获到 C++ 程序中的字符串中?
【发布时间】:2010-12-03 17:06:20
【问题描述】:

我正在使用 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);

但我不知道该怎么做才能捕获 python 解释器的输出 ....

【问题讨论】:

标签: c++ python redirect python-c-api python-embedding


【解决方案1】:

Python 解释器将在您的 C++ 进程中运行,因此它的所有输出都将发送到 C++ 程序本身的标准错误和标准输出。 this answer 中描述了如何捕获此输出。请注意,使用这种方法,您将不再需要在 Python 脚本中捕获输出 - 只需让它进入标准输出并在 C++ 中一次捕获所有内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 2013-05-18
    相关资源
    最近更新 更多