英文:
How to prevent Py_Finalize closing stderr?
问题
I have a c++ code that loads a python interpreter 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 behavior from the python side (os.dup/dup2)?
I tried replacing the above fdopen with:
stderr_dup = os.dup(sys.stderr.fileno())
But Py_Finalize still closes 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.
答案1
得分: 1
你可以更容易地从Python端解决这个问题:
stderr_dup = os.fdopen(sys.stderr.fileno(), 'wb', 0, closefd=False)
根据文档:
如果 closefd 参数为 False,并且给定的是文件描述符而不是文件名,当文件关闭时底层文件描述符将保持打开状态。
英文:
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.
答案2
得分: 1
你可以将 stderr 复制到另一个文件描述符中,然后在 Python 完成后将该文件描述符设置为 stderr。
int stderr_copy = dup(stderr);
// ... Python ...
dup2(stderr_copy, stderr);
英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论