问题
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