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
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):
Redirect stdout/stderr into a Python variable using Mark's solution: https://stackoverflow.com/a/4307737/1046299
Copy function PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags) from Python source code. It is located in file pythonrun.c
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.
Call the new function with your command, for example 1+1. Stdout should now receive the output 2.