如何在python中打印变量名及其值,这在调试过程中将非常有用?

2024-10-02 22:36:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经多次写过这样的文章:

print 'customer id: ', customerId

我想有一个函数,打印变量名和值

>>myprint(customerId)

>>customerId: 12345

Tags: 函数id文章customerprintcustomeridmyprint
2条回答

基本上,每次调用helper函数时,都需要将变量名手工输入到它的参数中,这与将字符串直接格式化为打印消息是一样的。你知道吗

另一种可能(没用?)可以是以下内容:

import re
regex = re.compile("__(.+)")
def check_value(checkpoint_name):
    print "============"
    print checkpoint_name
    print "============"
    for variable_name, variable_value in globals().items():
        if regex.match(variable_name) is None:
            print "%s\t:\t%s" % (variable_name, str(variable_value))
    print "============"

,它在每次调用的全局作用域中打印所有非系统保护的声明变量。要调用函数,请执行以下操作

 a = 0
 check_value("checkpoint after definition of a")

 b = 1
 check_value("checkpoint after definition of b")

您可以根据自己的需要自定义功能。我刚想到这个,不确定这是否是你想要的。。。你知道吗

完全按照您的要求进行操作需要在符号表中进行O(n)查找,这是非常糟糕的。你知道吗

如果可以传递与变量名对应的字符串,则可以执行以下操作:

import sys

def myprint(name, mod=sys.modules[__name__]):
    print('{}: {}'.format(name, getattr(mod, name)))

测试:

a=535
b='foo'
c=3.3

myprint('a')
myprint('b')
myprint('c')

将打印:

a: 535
b: foo
c: 3.3

您也可以通过传递第二个参数来打印来自另一个模块的变量,例如:

>>> import os
>>> myprint('pathsep', os)
pathsep: :

相关问题 更多 >