小编Jos*_* M.的帖子

尽管脚本是"纯粹的"python(自定义异常处理程序挂钩停止工作),但.py和.ipy文件的IPython行为不同

我编写了一个异常处理程序,用于在调用普通的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')
        # …
Run Code Online (Sandbox Code Playgroud)

python exception-handling ipython python-2.7 interactive-shell

5
推荐指数
0
解决办法
403
查看次数