pythonipdb

Shortcut for invoking ipdb?


ipdb is just great; wow. The thing is, when a script blows up, I still have to go into the code and add four lines that require not a ton of typing, but not nothing either. For example, let's say this is the bad line:

1 = 2

Naturally, I get this:

SyntaxError: can't assign to literal

If for whatever reason I wanted to debug that line and see what was going on just before that line (or somewhere else in the stack at that moment), I would typically change that line of code as follows:

try:
    1 = 2
except:
    import traceback;traceback.print_exc()
    import ipdb;ipdb.set_trace()

That gets the job done, but I'd love to be able to run a script in a "mode" where whenever ANYTHING blows up (assuming the exception is otherwise unhandled), I get the same result.

Does that exist?

*******EDIT*******

Thanks to @np8's response, I redid the driver script to look like this (where main is any arbitrary function):

if __name__ == "__main__":
    start = time.time()
    args = parser.parse_args()

    if args.verbosity > 1:
        from ipdb import launch_ipdb_on_exception
        with launch_ipdb_on_exception():
            print("Launching ipdb on exception!")
            main(start, args)

    else:
        print("NOT launching ipdb on exception!")
        main(start, args)

This allows me, from the command line, to determine whether exceptions should launch ipdb (i.e. when I'm developing) or not (i.e. when the script is running in production and therefore with a verbosity argument below 2, in this example).


Solution

  • You could use the launch_ipdb_on_exception context manager:

    # test.py
    from ipdb import launch_ipdb_on_exception
    
    with launch_ipdb_on_exception():
        print(x)
    

    Running the above will result into launching ipdb:

    python .\test.py
    NameError("name 'x' is not defined",)
    > c:\tmp\delete_me\test.py(4)<module>()
          2
          3 with launch_ipdb_on_exception():
    ----> 4     print(x)
    
    ipdb>