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

标签 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 调试器仅在断点期间显示值。因此我的问题是,如果我有一个协调人,可以做一些简单的事情吗?

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

最佳答案

有一个excellent solution由用户@ Anderson Carlos Woss 创建。 这里,改编为英语:

<小时/>

As discussed, one option for displaying variable debug is using the inspect module. With the help of the inspect.stack function you can check the context where the function was executed and access the local and global variables in this context. So, instead of passing the variable itself to function, you can only pass its name so that the function will be in charge of accessing its value by inspection. For this example I still used the tabulate module to format the output easily and legibly.

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']))

An example of use would be:

>>> 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

See on Repl.it

函数内调用示例

Debugging a local and a global variable:

author = "Anderson Carlos Woss"

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

hello('John Doe')

See on Repl.it

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

Hi, John Doe (by Anderson Carlos Woss)

However, for expression, like doing x + y * 2 the function will not work. It is possible to implement the function for this, but I believe it will be impractical. It will be much simpler for you to assign the expression to another variable and pass it to the function. For example:

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

Which shows:

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

关于python - 调试命令显示变量的名称和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52580892/

相关文章:

c - 函数总是返回无意义的值

Python 3D 绘图与数据,发生错误

debugging - 如何为 Prolog 使用有效的调试器/跟踪

c# - 如何让 Debug.WriteLine 与其他进程一起工作?

python - 如何通过组合数据框中的两个系列来添加新系列?

python - 捕获非整个训练、测试和验证分割中的所有数据

python - rawpy.Params中output_bps的含义

Python 和 BeautifulSoup 4/Selenium - 无法从 kicksusa.com 获取数据?

Python 内部中断函数

python - 从 Matlab 调用 Python - 如何调试 Python 代码?