在Python中打开/关闭打印语句的高效方法? [英] Efficient way of toggling on/off print statements in Python?
本文介绍了在Python中打开/关闭打印语句的高效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有10或15个非常有用的调试 print
在我的程序中(在不同的功能和 main
)。
I have 10 or 15 very useful debugging print
statements sprinkled throughout my program (in different functions and in main
).
我不会总是想要或需要日志文件。我有一个配置文件,我可以添加一个参数来打开或关闭打印语句。但是,我必须在每个打印声明之上添加一个这个参数值的保护检查。
I won't always want or need the log file though. I have a config file in which I could add a parameter to toggle print statements on or off. But then, I'd have to add a guard check for the value of this parameter above every print statement.
什么是更好的方法? $ b
What are some better approaches?
推荐答案
from __future__ import print_function
enable_print = 0
def print(*args, **kwargs):
if enable_print:
return __builtins__.print(*args, **kwargs)
print('foo') # doesn't get printed
enable_print = 1
print('bar') # gets printed
不幸的是你不能保留py2打印语法 print'foo'
sadly you can't keep the py2 print syntax print 'foo'
这篇关于在Python中打开/关闭打印语句的高效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文