Efficient way of toggling on/off print statements in Python? [duplicate]

折月煮酒 提交于 2019-12-25 05:48:04

问题


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.

What are some better approaches?


回答1:


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

sadly you can't keep the py2 print syntax print 'foo'



来源:https://stackoverflow.com/questions/32487941/efficient-way-of-toggling-on-off-print-statements-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!