在 python 交互模式下如何查看 class 中的变量值?

How can I see the value of a variable that is inside a class during python interactive mode?

当我 运行 使用 python -i file.py 的脚本并且我收到错误时,我想找出该变量的值。但是它在 class 中,而不是实例中。

class Foo:
    def func(self):
        action_dict = self.socket_resp() # a function that recieves some response from a socket. 
        print(action_dict['bar'])

python -i foo.py

KeyError no 'bar' in action_dict

action_dict

NameError: 名称 'action_dict' 未定义'

如何在交互模式下获取 action_dict 变量的值

是的,你可以得到它。来自 -i 的例外将在 sys.last_value 中可用。 import sys然后把sys.last_value保存到一个变量中!如果输入错误,异常将永远丢失!

然后你可以导入traceback模块并检查激活记录,其中包括所有调用帧中的局部变量!

因此我们得到:

% python3 -i file.py
Traceback (most recent call last):
  File "file.py", line 6, in <module>
    Foo().func()
  File "file.py", line 4, in func
    print(action_dict['bar'])
KeyError: 'bar'
>>> import sys
>>> exc = sys.last_value
>>> import traceback
>>> [*traceback.walk_tb(exc.__traceback__)][-1][0].f_locals
{'action_dict': {'foo': 'spam'}, 'self': <__main__.Foo object at 0x7f6aa2e6b978>}