python标准输出sys.stdout_使Python中的函数标准输出静音,而不会破坏sys.stdout并恢复每个函数调用...
只是為了補充別人已經說過的內容,Python 3.4引入了contextlib.redirect_stdout上下文管理器。它接受將輸出重定向到的文件(類)對象。
重定向到/ dev / null將抑制輸出:
In [11]: def f(): print('noise')
In [12]: import os, contextlib
In [13]: with open(os.devnull, 'w') as devnull:
....:? ? ?with contextlib.redirect_stdout(devnull):
....:? ? ? ? ?f()
....:
In [14]:
此解決方案可以用作裝飾器:
import os, contextlib
def supress_stdout(func):
def wrapper(*a, **ka):
with open(os.devnull, 'w') as devnull:
with contextlib.redirect_stdout(devnull):
func(*a, **ka)
return wrapper
@supress_stdout
def f():
print('noise')
f() # nothing is printed
在Python 2和3中都可以使用的另一種可能且偶爾有用的解決方案是將/ dev / null作為參數傳遞給f并使用函數的file參數重定向輸出print:
In [14]: def f(target): print('noise', file=target)
In [15]: with open(os.devnull, 'w') as devnull:
....:? ? ?f(target=devnull)
....:
In [16]:
您甚至可以target完全選擇:
def f(target=sys.stdout):
# Here goes the function definition
請注意,您需要
from __future__ import print_function
在Python 2中
總結
以上是生活随笔為你收集整理的python标准输出sys.stdout_使Python中的函数标准输出静音,而不会破坏sys.stdout并恢复每个函数调用...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软件项目管理面试题
- 下一篇: 你该知道的杂志分区和影响因子及最新表格下