如何抑制 Python 脚本中的所有打印信息? [英] How to suppress all the print info from the Python Script?
问题描述
是否有一种简单的方法可以全局抑制来自 python 脚本的所有打印信息?
Is there an easy way to suppress all the print info from the python script globally ?
有一个场景,为了调试目的,我在脚本中放入了大量打印信息,但是当用户运行时,我不希望脚本打印所有信息.
Have a scenario where I had put lot of print info in the script for debug purpose, but when the user runs I don't want the script to print all the infos.
因此,只有当我传递像 debug=1 之类的命令行参数时,打印才需要提供不应该打印的信息.
So only when I pass a command line argument like debug=1 or something like that, the print needs to provide the info else it shouldn't print.
简单地尝试过,
if sys.argv[1]:
debug=1
else:
debug=0
if debug:
print "Enabled debugging"
但是为此我需要在任何地方都包含 if 条件,而不是有什么简单的方法可以全局关闭打印信息?分享您的评论.
But for this I need to include the if condition everywhere, instead is there any easy way to shutdown the print info globally ? Share in your comments.
谢谢
推荐答案
您必须将标准输出重定向到/dev/null.以下是与操作系统无关的操作方式.
You will have to redirect stdout to /dev/null. Below is the OS agnostic way of doing it.
import os
import sys
f = open(os.devnull, 'w')
sys.stdout = f
这篇关于如何抑制 Python 脚本中的所有打印信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!