只是为了补充别人已经说过的内容,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中