[英]How can I see the value of a variable that is inside a class during python interactive mode?
When I run a script with python -i file.py and I recieve an error, I would like to find out the value of that variable. 当我使用python -i file.py运行脚本并且收到错误消息时,我想找出该变量的值。 However it is inside a class, and not an instance. 但是,它在类内部,而不是实例。
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 python -i foo.py
KeyError no 'bar' in action_dict KeyError在action_dict中没有'bar'
action_dict action_dict
NameError: name 'action_dict' is not defined' NameError:名称'action_dict'未定义'
How do I get the value of the action_dict variable in interactive mode 如何在交互模式下获取action_dict变量的值
Yes you can get it. 是的,你可以得到它。 The exception from -i
will be available in sys.last_value
. -i
的异常将在sys.last_value
。 First import sys
and save the sys.last_value
to a variable! 首先 import sys
并将sys.last_value
保存到变量中! If you typo, the exception will be lost for good! 如果您输入错误,则该异常将永远消失!
Then you can import the traceback
module and inspect the activation records, which includes local variables in all call frames! 然后,您可以导入traceback
模块并检查激活记录,其中包括所有调用帧中的局部变量!
Thus we get: 这样我们得到:
% 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>}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.