简体   繁体   English

Python:未处理的异常后如何控制命名空间?

[英]Python: how to control namespace after an unhandled exception?

Is there any way to control which namespace you'll end up in after an unhandled exception?有没有办法控制在未处理的异常之后你最终会进入哪个命名空间?

For example, in an IPython prompt, run myscript.py on a file with these contents:例如,在 IPython 提示符下,对包含以下内容的文件run myscript.py

def spam():
    ham = "ham"
    crash = 1/0
    eggs = "eggs"

if __name__ == '__main__':
    foo = "foo"
    spam()

it crashes out with the zero division, and returns to IPython prompt with foo now in the namespace, but no ham .它因零除法而崩溃,并返回到 IPython 提示符,现在名称空间中有foo ,但没有ham For some post mortem inspection, I want to return to the interpreter in the scope of the function spam() (ie ham would be available, eggs and foo would not).对于一些事后检查,我想返回 function spam()的 scope 中的解释器(即ham可用, eggsfoo不可用)。

We can access those things with pdb.set_trace() and re-running the code, but it would be great if there was a shortcut to step back a frame.我们可以使用pdb.set_trace()访问这些内容并重新运行代码,但如果有一个快捷方式可以退回一帧,那就太好了。

You can enable the automatic calling of pdb in the ipython prompt by typing %pdb .您可以通过键入%pdb在 ipython 提示符中启用 pdb 的自动调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM