脚本在python中运行时打印/查看所有变量

时间:2013-08-09 01:49:58

标签: python debugging python-2.7 error-handling

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

我已尝试过以下内容,但它无法实现我的目标:

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

5 个答案:

答案 0 :(得分: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__.

答案 1 :(得分:3)

我经常使用的一些非stdlib东西:

首先,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
>>> 

Here's一个有趣的视频(闪电话),作者在谈论q,如果有人有兴趣。

答案 2 :(得分: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

答案 3 :(得分:2)

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

h = inspect.currentframe()
for var, data in h.f_locals.items():
    print "Var {0} : {1}".format(var, data)

答案 4 :(得分: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)