python - 如何在我的代码中传递全局调试标志变量;我应该使用 argparse 吗?

标签 python logging argparse global debug-mode

假设我有一个主程序 (test.py) 和一个小实用程序 (test_utils.py),该程序具有由主程序调用的辅助函数。 我想通过传递 debug_flag bool 值来打开代码中的调试语句,该 bool 值通过 argparse 读取。

现在我希望我的 test_utils.py 程序中的函数也根据 debug_flag 的值打印调试语句。我总是可以将 debug_flag 作为参数添加到 test_utils.py 中的每个函数定义中,并在调用函数时传递参数,但是这里有更好的方法吗,比如 make debug_flag 一个全局变量?但是,如果我从 test.py 中声明 debug_flag 是全局的,那将如何导入到 test_utils.py 中?

这里最优雅/Pythonic 的方法是什么?

测试.py:

import argparse
from test_utils import summation

def main():
    args = get_args()
    debug_flag = True if args[debug] == 'True' else False
    print summation(5, 6, 7)

def get_args():
    parser = argparse.ArgumentParser(description='Test program')
    parser.add_argument('-d','--debug', help='Debug True/False', default=False)
    args = vars(parser.parse_args())
    return args

test_utils.py:

from test import debug_flag

def summation(x, y, z):
    if debug_flag:
        print 'I am going to add %s %s and %s' % (x, y, z)
    return x + y + z

EDIT1:澄清 - 如果我通过 argparse 传递调试标志,从而将 debug_flag 设置为 True - 这将如何传播到 test_utils.py 中的函数?

EDIT2:根据@joran-beasley 的建议,这就是我得到的。

测试.py:

import argparse
import logging
from test_utils import summation

def main():
    args = get_args()
    logging.getLogger("my_logger").setLevel(logging.DEBUG if args['debug'] == 'True' else logging.WARNING)
    print summation(5, 6, 7)

def get_args():
    parser = argparse.ArgumentParser(description='Test program')
    parser.add_argument('-d','--debug', help='Debug True/False', required=True)
    args = vars(parser.parse_args())
    return args

main()

测试工具.py

import logging

log = logging.getLogger('my_logger')

def summation(x, y, z):
    log.debug('I am going to add %s %s and %s' % (x, y, z))
    return x + y + z

当我运行 test.py 时,我得到:

$ python test.py -d True
No handlers could be found for logger "my_logger"
18

最佳答案

使用日志记录

# this logger will always now be logging.DEBUG level
logging.getLogger("my_logger").setLevel(logging.DEBUG if args.debug else logging.WARNING)

然后使用

log = logging.getLogger("my_logger")
...
log.warn("some text that should always be seen!")
log.debug("some debug info!")

然后您可以在具有多个日志记录级别的地方执行操作

log_level = logging.WARNING
if args.verbose > 0:
   log_level = logging.INFO
elif args.verbose > 3:
   log_level = logging.DEBUG

如果出于某种原因你需要检索 currentEffectiveLogLevel(在大多数情况下你真的不应该......当你想要调试级别输出时只需使用 log.debug)

logging.getLogger("my_logger").getEffectiveLevel()

[编辑澄清]

log = logging.getLogger('my_logger')

def summation(x, y, z):
   log.debug('I am going to add %s %s and %s' % (x, y, z)) # will not print if my_logger does not have an effective level of debug
   return x + y + z

print(summation(2, 3, 4))
log.setLevel(logging.DEBUG)
print(summation(4, 5, 6))

或者你可以写一个辅助函数

def is_debug():
    return logging.getLogger("my_logger").getEffectiveLevel() == logging.DEBUG

粗略地说,你总是可以做一些可怕的 hacky 废话,比如将它写入一个平面文件并读取它或使用真正的全局变量(比你想象的更难,还有很多边缘情况需要担心)

关于python - 如何在我的代码中传递全局调试标志变量;我应该使用 argparse 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49781573/

相关文章:

python - Tensorflow dataset.batch() 不显示真实的批量大小

php - 使用 COUNT、GROUP BY、ORDER BY MAX 过滤日志文件

node.js - Cat 显示日志中没有任何内容( express 服务器)

python - 如何从位于不同模块的两个类中选择一个

python - 用于运行带参数的 Python 程序的 Docker 文件

python - 允许 Argparse 参数的特定值

python - 使用 boto3 将 csv 导出到 dynamodb

c++ - 从一组非连续的连续二维切片创建一个 3d numpy 数组

java - Log4j 日志配置

python - ImportError:无法导入名称解包