1

我正在寻找一种在运行期间查看所有变量的方法,以便更轻松地调试。

我已经尝试了以下方法,但它不能按照我想要的方式工作:

import inspect

a = False
b = ""
c = "test"
d = {}
e = []
f = ["Test", "Test"]
g = ("One", "1", "Two", "2")


h = inspect.currentframe()
print h.f_locals

理想情况下,我希望它打印类似于下面的内容,或者只是让我看看什么变量有什么数据

a
False

b
""

c
test

d
{}

e
[]

f
test, test

g
One, 1, Two, 2

这样我可以很容易地看到变量及其数据......

在 VBA 中这很容易,因为您有一个包含所有变量的窗口。

提前致谢 - Hyflex

4

5 回答 5

5

您可以使用vars()

a = False
b = ""
c = "test"
d = {}
e = []
f = ["Test", "Test"]
g = ("One", "1", "Two", "2")
for k, v in vars().items():
    if not (k.startswith('__') and k.endswith('__')):
        print k,'--',v

输出:

a -- False
c -- test
b -- 
e -- []
d -- {}
g -- ('One', '1', 'Two', '2')
f -- ['Test', 'Test']

帮助vars

>>> print vars.__doc__
vars([object]) -> dictionary

Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
于 2013-08-09T02:01:49.017 回答
3

我经常使用的一些非标准库的东西:

首先,ipython 更有用的魔术函数之一:%whos

In [21]: a = 'hi'
    ...: bob = list()
    ...: 

In [22]: %whos
Variable   Type    Data/Info
----------------------------
a          str     hi
bob        list    n=0

%who只列出变量而不提供内容信息。

第二,q。您可以进行更强大的内联调试,甚至可以在代码中的任意位置打开交互式提示。

In [1]: def stuff():
   ...:     a = 'hi'
   ...:     b = 'whatever'
   ...:     c = [1,2,3]
   ...:     import q; q.d()
   ...:     return a,b
   ...: 

In [2]: stuff()
Python console opened by q.d() in stuff
>>> 

如果有人感兴趣,这是作者谈论 q 的有趣视频(闪电谈话)。

于 2013-08-09T03:22:08.787 回答
2
import inspect
import copy

# Store pre-existing attributes, which aren't generated by you.
uninteresting_keys = inspect.currentframe().f_locals.keys()
uninteresting_keys.append('uninteresting_keys')

a = False
b = ""
c = "test"
d = {}
e = []
f = ["Test", "Test"]
g = ("One", "1", "Two", "2")

# Make a copy, otherwise f_locals changes size during the for loops, which causes an error.
locals = copy.copy(inspect.currentframe().f_locals)
for key in locals:
#   if the attribute is not in our list of preexisting attributes, print it out with its` value:
    if key not in uninteresting_keys:
        print key
        print locals[key]
        print
于 2013-08-09T02:06:00.960 回答
2

如果你想使用inspect,你也可以遍历 .f_locals.items()

h = inspect.currentframe()
for var, data in h.f_locals.items():
    print "Var {0} : {1}".format(var, data)
于 2013-08-09T02:07:48.240 回答
2

您想要的数据都在您从中获得的数据中f_locals。这只是格式化和打印它的问题。您可能还想省略__special__名称。您可以简单地编写一个函数来执行此操作:

import inspect

def print_locals(frame=None):
    frame = frame or inspect.currentframe().f_back 
    locs = frame.f_locals
    spec = "%" + str(max(len(n) for n in locs)) + "s"
    for name in sorted(locs, key=str.lower):
       if not (name.startswith("__") and name.endswith("__")):
           print spec % name, "=", repr(locs[name])

每当您想要转储当前上下文时,您可以不带参数调用此函数,或者您可以轻松编写一个信号处理程序,在您按下时调用它^C

import signal

def sigint_handler(signum, frame):
    print_locals(frame)

signal.signal(signal.SIGINT,sigint_handler)
于 2013-08-09T02:19:40.860 回答