How To catch python stdout in c++ code

前端 未结 3 481
说谎
说谎 2020-11-27 14:45

I have a program which during it\'s run sometimes needs to call python in order to preform some tasks. I need a function that calls python and catches pythons stdout

3条回答
  •  盖世英雄少女心
    2020-11-27 15:25

    I know this question is old, but one part of the question has not been answered yet:

    "How to catch output of commands that don't directly write to the stdout of Python, like: 1+1 ?"

    Here are the steps (for Python 3.4):

    1. Redirect stdout/stderr into a Python variable using Mark's solution: https://stackoverflow.com/a/4307737/1046299

    2. Copy function PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags) from Python source code. It is located in file pythonrun.c

    3. Modify the PyRun_InteractiveOneObject function name and signature so that the new function takes a const char* (your command) as first parameter instead of a FILE*. Then you will need to use PyParser_ASTFromStringObject instead of PyParser_ASTFromFileObject in the function implementation. Note that you will need to copy the function run_mod as is from Python since it is called within the function.

    4. Call the new function with your command, for example 1+1. Stdout should now receive the output 2.

提交回复
热议问题