【问题标题】:Print / view all variables whilst a script is running in python在 python 中运行脚本时打印/查看所有变量
【发布时间】:2013-08-09 01:49:58
【问题描述】:

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

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

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 中这很容易,因为您有一个包含所有变量的窗口。

提前致谢 - 海福克斯

【问题讨论】:

  • IPython 或 pdb 可能值得研究。
  • pprint.pprint(locals()) 可以为您提供格式更好的局部变量 dict 显示,或者您可以编写一个函数来迭代它并按照您的需要打印它。不过,我会将答案留给对可用工具有更多了解的人。
  • @user2357112 我已经查看了 iPython,但我仍在尝试弄清楚如何使用它:S

标签: python debugging python-2.7 error-handling


【解决方案1】:

你可以使用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__.

【讨论】:

  • 效果很好,感谢Upvote :) 选择你的答案。非常感谢你:)
【解决方案2】:

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

首先,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的有趣视频(闪电谈话),如果有人感兴趣的话。

【讨论】:

  • 我已经查看了 iPython,但真的很难将我大量的代码转换成它并让它工作。我确信我的代码可以大幅改进,但我仍在学习,所以它缓慢而艰难
【解决方案3】:
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

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

      您想要的数据都在您从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)
      

      【讨论】:

        猜你喜欢
        • 2022-10-21
        • 1970-01-01
        • 2014-03-23
        • 2012-03-07
        • 2016-08-16
        • 1970-01-01
        • 1970-01-01
        • 2020-01-22
        • 1970-01-01
        相关资源
        最近更新 更多