pythonc++cythonpythoninterpreter

How to prevent Py_Finalize closing stderr?


I have a c++ code that loads a python interepter which uses stderr:

intereptor.pyx
stderr_dup = os.fdopen(sys.stderr.fileno(), 'wb', 0)

The problem is that after Py_Finalize is called, stderr is closed and I can't use it in c++. should I just reopen it in c++ by

open(stderr)

Or I can prevent this behaviour from the python side (os.dup/dup2)? I tired replacing the above fdopen with:

stderr_dup = os.dup(sys.stderr.fileno())

But Py_Finalize still closes stderr.


Solution

  • You could dup stderr into an additional file descriptor, and then set that file descriptor as stderr once the Python stuff is finished.

    int stderr_copy = dup(stderr);
    // ... Python ...
    dup2(stderr_copy, stderr);