我有运行 C 代码的 python 代码,这些代码会发送垃圾邮件 stdout 和 stderr。
我想抑制 stdout 和 stderr,而又无法修改 C 代码。作为伪代码,大致为:
def external_api_I_cant_control():
C code that outputs to stdout & stderr # this is not a subprocess
# call which I can redirect
# its stdout & stderr. Rather,
# it's a wrapper for it so there
# is nothing I can do to control its
# FD
def do_stuff():
external_api_I_cant_control()
我的代码正在使用 python bla.py
运行,因此,我可以使用 python bla.py 2>/dev/null 重定向
p>
stderr
code>,但这并不能解决我的问题,因为一些垃圾邮件是发送到 stdout
的,而我无法重定向 stdout
- 因为我需要其中一些。
是否可以在我的代码中执行相当于 shell stdout 重定向的操作?
到目前为止我尝试过:
contextlib.redirect_stdout
- 将
sys.stdout
和sys.__stdout__
替换为open(os.devnull, 'w')
我想要的结果相当于将我的 bla.py
分成 3 个并按如下方式运行:
python bla0.output.is.legit.py
python bla1.output.should.be.disregarded.py &> /dev/null
python bla2.output.is.legit.again.py
实现这一目标的方法是什么?
最佳答案
这是 os.dup2() 的工作。您想要的代码由三个阶段组成:
- 备份原始 stdout 和 stderr
- 用指向
/dev/null
的文件句柄替换 stdout 和 stderr - 恢复备份(运行所需的代码后)。
# create a backup of stdout and stderr
orig_stdout_fd = os.dup(1)
orig_stderr_fd = os.dup(2)
# make the original stdout and stderr point to /dev/null
devnull = open('/dev/null', 'r+')
os.dup2(devnull.fileno(), 1)
os.dup2(devnull.fileno(), 2)
# run your C code here
os.write(1, b"This would normally go to stdout\n")
# put the originals back
os.dup2(orig_stdout_fd, 1)
os.dup2(orig_stderr_fd, 2)
os.close(orig_stdout_fd)
os.close(orig_stderr_fd)
关于python - 重定向当前正在运行的 python 进程的 stdout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68716139/