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中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值