Jos*_* M. 5 python exception-handling ipython python-2.7 interactive-shell
我编写了一个异常处理程序,用于在调用普通的python异常挂钩之前记录代码中所有未捕获的异常.Python和iPython的实现方式略有不同.我发现iPython这样做的方式只有在交互式会话中运行时才有效,或者当使用".ipy"文件扩展名时,尽管我不相信我使用的是任何"魔术".即使脚本名为.py并且是'Pure python',常规的python方式也无法在ipython中运行.
我想要一种方法能够在脚本中为iPython设置我自己的异常挂钩,即使它是从命令行调用为".py"文件.
示例代码testcase.py:
import sys
def my_exc(exc_type, exc_value, exc_traceback):
"""Regular Python exception handler with inputs mirroring sys.excepthook"""
print('\nDoing Custom Stuff (Python exc handler)\n')
# Call the old sys.excepthook as well
sys.__excepthook__(exc_type, exc_value, exc_traceback)
def imy_exc(shell, exc_type, exc_value, exc_tb, tb_offset=None):
"""IPythonic exception handler, following instructions in
set_custom_exc here:
http://ipython.org/ipython-doc/stable/api/generated/IPython.core.interactiveshell.html"""
print('\nDoing Custom Stuff (iPython exc handler)\n')
# Do regular IPython stuff as well
shell.showtraceback((exc_type, exc_value, exc_tb), tb_offset=tb_offset)
try:
__IPYTHON__
from IPython import get_ipython
shell = get_ipython()
if shell:
print('Shell Active')
# Set my custom exception handler for the current IPython shell
get_ipython().set_custom_exc((Exception,), imy_exc)
else:
print('In IPython, but no active shell')
sys.excepthook = my_exc
except NameError:
print('NameError, falling back on regular Python way')
# use the standard python excepthook override
sys.excepthook = my_exc
def makeproblem():
1/0
makeproblem()
Run Code Online (Sandbox Code Playgroud)
行为:
作品:
1. $ ipython testcase.ipy
- result: "shell active", "Doing Custom Stuff (iPython exc handler)""
2. $ ipython -c="execfile('testcase.py')
- result: "NameError, falling back on regular Python way", "Doing Custom Stuff (Python exc handler)" (This one is particularly puzzling)
3. $ python testcase.py
- result: "NameError, falling back on regular Python way", "Doing Custom Stuff (Python exc handler)"
4. $ ipython
In[0]: execfile('testcase.py')
or
In[0]: %paste #pasting testcase.py
- result: "shell active", "Doing Custom Stuff (iPython exc handler)""
Run Code Online (Sandbox Code Playgroud)
不起作用:
1. $ ipython testcase.py
- result: "Shell Active", no override statement
2. $ ipython -c="% run 'testcase.py'"
- result: "Shell Active", no override statement
Run Code Online (Sandbox Code Playgroud)
%run vs execfile行为告诉我,它与在一个自包含的命名空间中运行的脚本有关,但我无法弄明白.这可能是一个红鲱鱼.我得到的另一个提示是,如果我在上面的测试用例脚本中使用inspect来转储帧,那么工作的情况下会调用顶部的interactiveshell,否则不会出现:
(<frame object at 0x10264b500>, '/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/IPython/core/interactiveshell.py', 2883, 'run_code', ['exec(code_obj, self.user_global_ns, self.user_ns)\n'], 0)
(<frame object at 0x10264a790>, '/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/IPython/core/interactiveshell.py', 2827, 'run_ast_nodes', ['if self.run_code(code):\n'], 0)
(<frame object at 0x10263eda0>, '/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/IPython/core/interactiveshell.py', 2741, 'run_cell', ['interactivity=interactivity, compiler=compiler)\n'], 0)
(<frame object at 0x10263e7c0>, '/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/IPython/core/interactiveshell.py', 2604, 'safe_execfile_ipy', ['self.run_cell(cell, silent=True, shell_futures=False)\n'], 0)
Run Code Online (Sandbox Code Playgroud)