【发布时间】:2014-10-27 17:37:17
【问题描述】:
出于调试目的,我想编写一个函数来执行此操作:
- 如果 debug_mode == 0 不回显任何消息。
- 如果 debug_mode == 1 使用 print() 将消息回显到标准输出
- 如果 debug_mode == 2 将消息回显到日志文件中
我曾想过用函数装饰器(我以前从未使用过)来做到这一点。
实际上,我想替换一些print(),我在其中添加了一些点来显示中间值,同时了解函数装饰器。
我不想创建一个类来做到这一点。这是我的方法,但它不起作用:
import logging
FORMAT = '%(asctime)s %(levelname)s %(message)s %(funcName)s'
logging.basicConfig(filename='example.log', level=logging.DEBUG, format=FORMAT, datefmt='%m/%d/%Y %I:%M:%S %p')
def debug(func):
def _debug(deb=0, *args, **kwargs):
if deb == 1:
print(msg)
func(*args, **kwargs)
if deb == 2:
logging.debug(msg)
return _debug
@debug
def echo(msg, deb=0):
pass
if __name__ == "__main__":
debug_mode = 1
echo("This is a debugging message!", debug_mode)
如果我没有传递参数 debug_mode 会更好,并且在装饰器函数中我可以直接从__main__ 使用调试状态。
【问题讨论】:
-
为什么不将调试设置设为全局?
-
@bereal 如果找不到其他解决方案,那是我计划的解决方案。我曾经尽量避免使用全局变量。
-
这里也一样,但是如果世界上有一个全局变量的位置,那么它就是调试和日志记录。你也可以依赖一个环境变量,如果不需要调试,
debug甚至可以返回原始函数。 -
为什么不使用日志模块?打印调试信息很麻烦,任何诸如“何时刷新”之类的琐碎事情都可能会影响 print() 调用和效果出现之间的时间差。
标签: python python-3.x python-decorators