Python:打印变量的名称和值? [英] Python: Print a variable's name and value?

查看:296
本文介绍了Python:打印变量的名称和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调试时,我们经常会看到类似以下的打印语句:

When debugging, we often see print statements like these:

print x        # easy to type, but no context
print 'x=',x   # more context, harder to type
12
x= 12

如何编写一个将接受变量或变量名称并打印其名称和值的函数?我只对调试输出感兴趣,不会将其合并到生产代码中。

How can write a function that will take a variable or name of a variable and print its name and value? I'm interested exclusively in debugging output, this won't be incorporated into production code.

debugPrint(x)    #  or
debugPrint('x')
x=12


推荐答案

您可以只使用 eval

def debug(variable):
    print variable, '=', repr(eval(variable))

或更一般地说(它实际上在调用函数的上下文中有效,并且不会在 debug('variable')上中断,而仅在CPython上有效):

Or more generally (which actually works in the context of the calling function and doesn't break on debug('variable'), but only on CPython):

from __future__ import print_function

import sys

def debug(expression):
    frame = sys._getframe(1)

    print(expression, '=', repr(eval(expression, frame.f_globals, frame.f_locals)))

您可以执行以下操作:

>>> x = 1
>>> debug('x + 1')
x + 1 = 2

这篇关于Python:打印变量的名称和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆