如何防止Py_Finalize关闭stderr?

huangapple go评论79阅读模式
英文:

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);

huangapple
  • 本文由 发表于 2023年5月10日 15:05:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76215743.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定