首页 > 解决方案 > 过滤 print() 调用?在全局或每个模块级别?

问题描述

我的 utils.py 中有以下用于调试信息的函数...

 say = print
 log = print

我想以这种方式声明它们,以便我可以打开/关闭它们。如果可能,以每个模块为基础。

假设我想测试一些东西并启用/禁用打印......

我不想使用日志记录,因为它太麻烦并且需要更多输入..

我正在使用它进行快速调试并最终删除这些打印


在 utils.py

say = print
log = print

def nope(*args, **kwargs): return None

在blah.py

from utils import *
class ABC:
  def abc(self): say(111)

在 ipython 中:

from blah import *
a = ABC()
a.abc()
111
say(222)
222

say = nope
a.abc(111)
111
say(222)
None 

标签: pythondebugging

解决方案


您可以随时重新定义 say/log 以便以后什么都不做。

Python 3.8.2 (default, Apr 27 2020, 15:53:34)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> say = print
>>> say("hello")
hello
>>> def say(*args, **kwargs):
...  return None
...
>>> say("hello")
>>>

推荐阅读