5

我编写了一个异常处理程序,旨在在调用普通 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()

行为:

作品:

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)""

不起作用:

1. $ ipython testcase.py
- result: "Shell Active", no override statement

2. $ ipython -c="% run 'testcase.py'"
- result: "Shell Active", no override statement

%run vs execfile 行为向我表明它与在自包含命名空间中运行的脚本有关,但我无法弄清楚。不过,这可能是一个红鲱鱼。我得到的另一个提示是,如果我在上面的测试用例脚本中使用检查转储帧,则工作的案例对顶部的交互式外壳有以下调用,否则不会出现:

(<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)
4

0 回答 0