Opening an IPython shell on any (uncaught) exception

后端 未结 2 1943
猫巷女王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!)

提交回复
热议问题