Skip to content

Instantly share code, notes, and snippets.

@naftaliharris
Last active January 2, 2016 09:39
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save naftaliharris/8284193 to your computer and use it in GitHub Desktop.
Save naftaliharris/8284193 to your computer and use it in GitHub Desktop.
An enhancement to the "python" executable that automatically launches you into a debugger if your code throws an exception.
#!/bin/bash
# An enhancement to the "python" executable that automatically launches you into the python debugger on error.
#
# Use it like you would the "python" executable, for example:
# $ trypy somefile.py
# or
# $ trypy somefile.py arg1 arg2
#
# EXAMPLE:
# $ cat fails.py
# import sys
# print sys.argv[1]
# print 1 / 0
# $ trypy fails.py hi
# hi
# Traceback (most recent call last):
# File "<string>", line 6, in <module>
# File "fails.py", line 3, in <module>
# print 1 / 0
# ZeroDivisionError: integer division or modulo by zero
# > /path/to/fails.py(3)<module>()
# -> print 1 / 0
# (Pdb)
#
# By Naftali Harris, with great thanks to
# http://stackoverflow.com/questions/242485/starting-python-debugger-automatically-on-error#answer-242514
# for showing how to enter the debugger on failure!
if [[ $# -lt 1 ]]
then
echo "Usage:"
echo "$ `basename $0` somefile.py"
echo "$ `basename $0` somefile.py arg1 [arg2] ..."
exit -1
fi
python -c "
import sys
sys.argv = sys.argv[1:] # remove '-c'
del sys # remove sys so stay clean
try:
execfile('$1')
except:
import sys, traceback, pdb
type, value, tb = sys.exc_info()
traceback.print_exc()
pdb.post_mortem(tb)
" "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment