Python: how to control namespace after an unhandled exception?

偶尔善良 提交于 2019-12-24 10:04:07

问题


Is there any way to control which namespace you end up in after an unhandled exception? For example, if I'm at an ipython prompt and I go run blah.py on a file with these contents:

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

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

it crashes out obviously but returns me to an ipython prompt, with foo now in the namespace (and any previously existing foo is now overwritten with 'foo'). But no ham. For some post mortem inspection, it is often the case that I would rather be returned to the interpreter in the scope of the function spam() - so that ham would be visible, eggs and foo would not...

I'm aware I can access those things with pdb.set_trace(), but it would be great if there was an easier shortcut, because I find the ipython prompt nicer to poke around in. At the moment I'm often copying the function's code into global namespace and inspecting from there.


回答1:


You can enable the automatic calling of pdb in the ipython prompt by typing %pdb.



来源:https://stackoverflow.com/questions/6338889/python-how-to-control-namespace-after-an-unhandled-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!