![]() |
|
Python Automatic Debugger - Printable Version +- Sinisterly (https://sinister.li) +-- Forum: Coding (https://sinister.li/Forum-Coding) +--- Forum: Python (https://sinister.li/Forum-Python) +--- Thread: Python Automatic Debugger (/Thread-Python-Automatic-Debugger) |
Python Automatic Debugger - abbietmp - 06-26-2021 Ever wish Python would just give you a debugger whenever an unhandled exception is raised? Me too! Here's how we can do that. You need to create or pick a directory. This directory should remain empty except for the file we're going to create or only ever hold python modules you want to be able to import without all that package nusence. What we're going to do is add this directory to the path Python searches when looking to import modules. We do this by setting the PYTHONPATH environment variable in one of our .profile, .bashrc, or other shell config file you use for this sort of thing. If you've never set an environment variable, just google how to do it. You can do this on Windows, you just have to follow instructions for adding a new environment variable, use Windows style path names, and reboot once you've set this all up. Code: export PYTHONPATH=/path/to/dirNow we put the following in /path/to/dir/sitecustomize.py (that filename is important, but the directory is whatever you set PYTHONPATH to). Whenever python starts running it attempts to import the sitecustomize module. This means we can have Python execute code when we run other python programs or start the Python REPL. The code below changes the sys.excepthook function to a new function. The sys.excepthook function is called whenever an exception reaches the top of the call stack without an exception handler. The default function we're overwriting is what prints the traceback you're used to and then exits the program. Our new function will instead do one of 3 things:
Code: import bdb, pdb, sys, traceback
def excepthook(ex_type, ex_val, ex_tb):
"""
Custom exception handler to provide PDB postmortems.
Arguments:
ex_type Exception
Class of ex_val.
ex_val Exception
Actual exception object.
ex_tb trackback
Call traceback object.
"""
if ex_type in (KeyboardInterrupt, bdb.BdbQuit):
return
elif ex_tb and not hasattr(sys, "ps1"):
traceback.print_exception(ex_type, ex_val, ex_tb)
pdb.post_mortem(ex_tb)
return
else:
sys.__excepthook__(ex_type, ex_val, ex_tb)
return
sys.excepthook = excepthookGo forth and break some shit! |