临时重定向 stdout/stderr [英] Temporarily Redirect stdout/stderr
问题描述
是否可以在 Python 中临时重定向 stdout/stderr(即在方法的持续时间内)?
Is it possible to temporarily redirect stdout/stderr in Python (i.e. for the duration of a method)?
当前解决方案的问题(我起初记得但后来忘记了)是它们不重定向;相反,它们只是完全替换了流.因此,如果一个方法有一个本地副本,因为任何原因(例如,因为流作为参数传递给某物),它就不会工作.
The problem with the current solutions (which I at first remembered but then forgot) is that they don't redirect; rather, they just replace the streams in their entirety. Hence, if a method has a local copy of one the variable for any reason (e.g. because the stream was passed as a parameter to something), it won't work.
有什么解决办法吗?
推荐答案
解决某些函数可能将 sys.stdout
流缓存为局部变量从而替换全局 的问题sys.stdout
在该函数内不起作用,您可以在文件描述符级别重定向 (sys.stdout.fileno()
) 例如:
To solve the issue that some function might have cached sys.stdout
stream as a local variable and therefore replacing the global sys.stdout
won't work inside that function, you could redirect at a file descriptor level (sys.stdout.fileno()
) e.g.:
from __future__ import print_function
import os
import sys
def some_function_with_cached_sys_stdout(stdout=sys.stdout):
print('cached stdout', file=stdout)
with stdout_redirected(to=os.devnull), merged_stderr_stdout():
print('stdout goes to devnull')
some_function_with_cached_sys_stdout()
print('stderr also goes to stdout that goes to devnull', file=sys.stderr)
print('stdout is back')
some_function_with_cached_sys_stdout()
print('stderr is back', file=sys.stderr)
stdout_redirected()
重定向 sys.stdout.fileno()
到给定的文件名、文件对象或文件描述符(示例中为 os.devnull
).
stdout_redirected()
redirects all output for sys.stdout.fileno()
to a given filename, file object, or file descriptor (os.devnull
in the example).
stdout_redirected()
和 merged_stderr_stdout()
在这里定义.
stdout_redirected()
and merged_stderr_stdout()
are defined here.
这篇关于临时重定向 stdout/stderr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!