Python debugger notes.
- python default built in debugger, very basic.
- Doc (official)
Add in code to create break
import pdb; pdb.set_trace()
s: step n: next unt : until r: return c: continue, stop only at breakpoint j <lineno>: jump p <exp> : print evaluated expression pp <exp> : pretty-print q: quit
sim to ipdb, but less buggy?
recommended, uses terminal based GUI.
import pudb; pudb.set_trace()
To run from beginning
? : help C-p: change appearance ! c: continue n: next j/k: up/down b: set breakpoint
- Uses ipython, requires ipython
- recommended, but might be buggy.
pip install ipdb
import ipdb; ipdb.set_trace()
s: step into n: step over c: continue to next breakpoint ?: help ? n: more help on 'n' l: more context
- Pycharm debugger: highly recommended
- Pydev: also highly recommended, uses Eclipse, it is also used by Pycharm
- ptvs (Visual Studio)
There’s a nice trick to enable this behavior for standard Python code run at the command line. Write the body of your code inside a main() function, then call it using the following toplevel block:if __name__ == "__main__": try: main() except KeyboardInterrupt: # allow ctrl-C raise except Exception as e: import sys, traceback, pdb print e type, value, tb = sys.exc_info() traceback.print_exc() pdb.post_mortem(tb)
This will catch any exceptions and throw you into PDB in the context where the exception was raised. You probably don’t want to leave it in production code, but it’s super useful for development.
Debugging messages, use “warning”
import warnings ... warnings.warn("Some warning",DeprecationWarning)