我尝试自定义的行为sys.excepthook
如所描述的配方 。
在IPython中:
:import pdb, sys, traceback
:def info(type, value, tb):
: traceback.print_exception(type, value, tb)
: pdb.pm()
:sys.excepthook = info
:--
>>> x[10] = 5
-------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
NameError: name 'x' is not defined
>>>
pdb.pm()
不会被调用。 看来, sys.excepthook = info
并不在我的Python 2.5的安装工作。
IPython中,你正在使用,而不是正常的Python交互shell的这些,捕获所有异常本身并没有采用sys.excepthook。 运行它ipython -pdb
,而不是仅仅ipython
,它会自动调用PDB在未捕获的异常,就如同你想与你的excepthook做。
你写了这五年后,IPython中仍然以这种方式工作,所以我想一个解决方案可能是有用的人使用Google这个。
IPython的替换sys.excepthook
每次执行一行代码的时间,所以你sys.excepthook压倒一切没有影响。 此外,IPython的甚至不叫sys.excepthook
,它捕获所有异常并处理他们自己之前的事情走到这一步。
要覆盖异常处理程序,同时IPython中运行时,您可以在自己的壳的猴补丁showtraceback
方法。 例如,这里就是我重写给什么看起来像一个普通的Python回溯(因为我不喜欢的IPython如何冗长的是):
def showtraceback(self):
traceback_lines = traceback.format_exception(*sys.exc_info())
del traceback_lines[1]
message = ''.join(traceback_lines)
sys.stderr.write(message)
import sys
import traceback
import IPython
IPython.core.interactiveshell.InteractiveShell.showtraceback = showtraceback
这个工作在两个正常的终端控制台和Qt控制台。
见这太问题 ,并确保没有东西在你的sitecustomize.py
防止调试以交互模式。
扩大对克里斯的回答,您可以使用其他功能像一个装饰你自己的功能添加到jupyters showbacktrace:
from IPython.core.interactiveshell import InteractiveShell
from functools import wraps
import traceback
import sys
def change_function(func):
@wraps(func)
def showtraceback(*args, **kwargs):
# extract exception type, value and traceback
etype, evalue, tb = sys.exc_info()
if issubclass(etype, Exception):
print('caught an exception')
else:
# otherwise run the original hook
value = func(*args, **kwargs)
return value
return showtraceback
InteractiveShell.showtraceback = change_function(InteractiveShell.showtraceback)
raise IOError