Opening an IPython shell on any (uncaught) exception

后端 未结 2 1942
猫巷女王i
猫巷女王i 2021-01-15 13:44

I have defined the following (embedded) shell in Python:

from IPython.config.loader import Config
cfg = Config()
prompt_config = cfg.PromptManager
prompt_con         


        
相关标签:
2条回答
  • 2021-01-15 14:02

    I think it's hardly possible to let the exception pass all the way through the call stack to find out whether or not someone would catch and handle it in the end, and then return to the scope where it was first raised. That original scope is gone, when the exception popped out of it.

    Your best bet may be to wrap all the parts where you want your shell to come up to handle an exception with a dedicated try ... except block, as in the following:

    try: 
       pass # stuff that may raise an exception
    except KeyboardInterrupt:
       # some exception you want to handle
       raise 
    except SystemExit:
       # another exception you want to handle
       raise 
    except: 
       # get a hand on any unhandled exception
       ipshell(traceback.format_exc())
    

    (Not sure if this can be implemented more elegantly. I'd be very interested in a better solution as well!)

    0 讨论(0)
  • 2021-01-15 14:12

    Defining the following in my ipython shell seems to do what you want:

    def custom_exc(shell, etype, evalue, tb, tb_offset=None):
        shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset)
        ipshell()
    
    get_ipython().set_custom_exc((Exception,), custom_exc)
    
    0 讨论(0)
提交回复
热议问题