with HiddenPrints():
print("This will not be printed")
print("This will be printed as before")
这更安全,因为您不能忘记重新启用stdout,这在处理异常时尤其重要。
# This is an example of not-so-good solution
# without 'with' context manager statement.
try:
disable_prints()
something_throwing()
# enable_prints() This wouldn't be enough!
except ValueError:
handle_error()
finally:
enable_prints() # That's where it needs to go.
正如@Alexander Chzhen所建议的,使用上下文管理器比调用一对状态更改函数更安全。
但是,您不需要重新实现上下文管理器—它已经在标准库中了。可以用
contextlib.redirect_stdout
重定向stdout
(文件对象,print
使用),也可以用contextlib.redirect_stderr
重定向stderr
。Python允许您用任何文件对象覆盖标准输出(stdout)。这应该跨平台工作,并写入空设备。
如果不希望打印该函数,请在该函数之前调用
blockPrint()
,并在希望继续时调用enablePrint()
。如果要禁用全部打印,请在文件顶部开始阻塞。基于@fakerainbrigan解决方案,我建议一个更安全的解决方案:
然后你可以这样使用它:
这更安全,因为您不能忘记重新启用stdout,这在处理异常时尤其重要。
如果您忘记了
finally
子句,那么您的print
调用将不再打印任何内容。使用with
语句,这是不可能的。使用
sys.stdout = None
是不安全的,因为有人可以调用sys.stdout.write()等方法相关问题 更多 >
编程相关推荐