How to prevent Py_Finalize closing stderr?

107 Views Asked by At

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.

2

There are 2 best solutions below

0
Jack Humphries On BEST ANSWER

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);
8
Botje On

You can solve this from the Python side far more easily:

stderr_dup = os.fdopen(sys.stderr.fileno(), 'wb', 0, closefd=False)

From the documentation:

If closefd is False and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed.