简体   繁体   English

在python交互模式下,如何查看类内部变量的值?

[英]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.

相关问题 python:如果在交互模式下阻塞,如何退出 - python:how to exit if block during interactive mode 在 python 交互模式下如何导入手工模块 - In python interactive mode how can i import a handmade module 如何在 Python 中访问 class 内的全局变量 - How can I access global variable inside class in Python 如何在python中的函数内给变量另一个值? - how can I give a variable another value inside a function in python? 如何从 Python 中的另一个类更改变量的值? - How can I change the value of a variable from another class in Python? 将 Python 作为子进程调用时,是否可以强制它以交互模式运行? - When calling Python as a subprocess, can I force it to run in interactive mode? 我可以在交互模式下访问python中的sys.argv吗? - Can I access sys.argv in python in interactive mode? 我可以在python交互模式下有多个matplotlib绘图窗口吗? - Can I have multiple matplotlib plot windows in python interactive mode? 在非交互式 SSH 模式下运行命令时,如何使用相对路径 Python? - How can I use a relative Python path when running a command in non-interactive SSH mode? 如何在jupyter-notebook / python交互模式下使用gettext? - How can I use gettext in jupyter-notebook/python interactive mode?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM