显示变量名称和值的调试命令吗?

时间:2018-09-30 18:30:00

标签: python python-3.x debugging

通常在需要在运行时调试变量的值 时,我会使用print()

但是当变量很多时,我需要识别变量的名称以及值。

这样,随着多个变量的出现,打印变得更加费力

 print ("x=", x, "y=", y, "x+y*2=", x+y*2)

理想的情况是使用简单的命令,例如:

 debug (x, y, x + y * 2)

...将自动添加变量,如上图所示。

这个想法只是有一个简单而快速的命令来促进调试,因为在此过程中,通过构建一系列仅用于调试的命令来失去焦点并不是一件好事。

我已经使用了Pycharm,它具有出色的调试功能。问题在于,要在运行时跟踪值的演变,我必须使用print(),因为Pycharm调试器仅在断点期间显示值。因此,我的问题是,如果我有一个主持人,那么简单吗?

有没有简单的命令可以做到这一点?

1 个答案:

答案 0 :(得分:0)

用户@ excellent solution创建了一个Anderson Carlos Woss。 在这里,适用于英语:


  

如前所述,显示变量 debug 的一种方法是使用inspect模块。借助inspect.stack函数,您可以检查函数执行的上下文,并在此上下文中访问局部变量和全局变量。因此,只能将其名称传递给函数,而不是将变量本身传递给函数,以便函数可以通过检查来访问其值。对于此示例,我仍然使用制表模块来轻松,清晰地格式化输出。

import inspect
import tabulate


def debug(*args):

# Find the context of who called the debug function:
context = inspect.stack()[1][0]

# Results to be displayed:
result = []

# Scroll through all the variables to display:
for name in args:
    # Checks whether it is a local variable in context:
    if name in context.f_locals:
        result.append([name, context.f_locals[name]])
    # Checks whether it is a global variable in context:
    elif name in context.f_globals:
        result.append([name, context.f_globals[name]])
    # Variable not found in context:
    else:
        result.append([name, 'Not found'])

# Displays the results in tabular form:
print(tabulate.tabulate(result, headers=['Variable', 'Content']))
  

使用示例为:

>>> x, y, nome = 1, 2, 'Anderson Carlos Woss'
>>> debug('x', 'y', 'nome', 'foo')

Variable    Content
----------  --------------------
x           1
y           2
nome        Anderson Carlos Woss
foo         Não encontrada
  

请参见Repl.it

函数内的示例调用

  

调试局部变量和全局变量

author = "Anderson Carlos Woss"

def hello(name):
    debug('name', 'author')
    print(f'Hi, {name} (by {author})')

hello('John Doe')
  

请参见Repl.it

Variable    Content
----------  --------------------
name        John Doe
author      Anderson Carlos Woss

Hi, John Doe (by Anderson Carlos Woss)
  

但是,对于表达式,就像执行x + y * 2一样,该函数不会   工作。可以实现此功能,但是我相信   这将是不切实际的。您可以更轻松地分配   将表达式表达给另一个变量,然后将其传递给函数。对于   例如:

>>> x, y = 1, 2
>>> x_plus_2y = x + 2*y
>>> debug('x', 'y', 'x_plus_2y')
  

哪个显示:

Variable    Content
----------  -------
x                 1
y                 2
x_plus_2y         5