我正在尝试编写一个函数来帮助我进行调试。我不想时不时地插入几个打印语句,而是想插入一个单行调试语句。我期望完成的是这样的函数可以重复使用:我想在多个函数中使用它,以便打印不同的变量集。
我特别想做的是:
def _debugFunction(var_list):
global debug_flag
if debug_flag:
print 'START DEBUGGING:'
< magic code >
print 'END DEBUGGING'
def foo_function(n):
x = 1
y = 2
z = 'string'
debugFunction([x, y, z])
return x + y
所以当我设置 debug_flag = True
并调用 foo 时,输出是:
START DEBUGGING:
x = 1
y = 2
z = 'string'
END DEBUGGING
3
然后,如果我设置 debug_flag = False
并调用 foo,输出为:
3
为了做到这一点,我需要在运行时获取作为参数传递给 debugFunction()
的变量的名称,并将其与它们的值一起打印。
我搜索过其他帖子,但找不到直接的答案。
How to get a variable name as a string in Python?
retrieving a variable's name in python at runtime?
据我所知,人们被告知要使用日志记录模块。我查看了它并尝试实现它的一小部分,但我无法记录任何内容(不过我不会投降)。
我还读到人们会指向 __dict()__
、vars()
或 dir()
,但只是无法理解如何使用它们。此外:如果我尝试将它们应用于我的变量,我只会得到错误或无意义的(对我来说;)输出。
有没有办法做到这一点?这是太糟糕的做法吗?如果是这样的话:什么是好的做法?
PS:也许没有必要浪费精力尝试实现它,而是花时间了解如何正确使用日志记录模块。
最佳答案
I've also read that people get pointed to dict(), vars(), or dir(), but just can't understand how to use them.
您是否尝试查看这些功能的文档?例如,vars
:
… Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.
好的,locals
是什么意思?做?查看文档:它为您提供了一个字典,将函数中的每个局部名称映射到它的值。因此,如果您不想同时传递名称和值,请传递 locals()
字典和名称:
def foo_function(n):
x = 1
y = 2
z = 'string'
debugFunction(locals(), ['x', 'y', 'z'])
return x + y
def _debugFunction(localdict, var_list):
global debug_flag
if debug_flag:
print 'START DEBUGGING:'
for name in var_list:
print('{}: {}'.format(name, localdict[name]))
print 'END DEBUGGING'
就是这样。除了我可能会稍微更改接口(interface)以使用 *var_list
或更简单的我可以 split
的字符串,并且使其在简单情况下更易于使用,默认打印所有本地人:
def _debugFunction(localdict, var_list=''):
var_list = var_list.split()
if not var_list:
var_list = localdict.keys()
现在你可以这样做了:
_debugFunction(locals(), 'x y z')
或者只是:
_debugFunction(locals())
关于python - 打印 'var' = var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24941504/