Skip to content

Instantly share code, notes, and snippets.

@hcarvalhoalves
Last active February 9, 2017 17:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hcarvalhoalves/7587621 to your computer and use it in GitHub Desktop.
Save hcarvalhoalves/7587621 to your computer and use it in GitHub Desktop.
import sys
import os
from pdb import Pdb
banner = """Usage:
%(command)s @<module>:<linenumber> ... <filename> <args>
Use @<module>:<linenumber> to set one or multiple breakpoints.
<module> may be an absolute path to a module file, or relative to sys.path.
Example:
%(command)s @mypackage/mymodule.py:42 myscript.py --some-argument
"""
def parse_args(args):
breakpoints = map(lambda a: a[1:], filter(lambda a: a.startswith('@'), args))
other = filter(lambda a: not a.startswith('@'), args)
return breakpoints, other
def main():
breakpoints, original_args = parse_args(sys.argv[1:])
if not original_args or sys.argv[1] in ("--help", "-h"):
sys.stderr.write(banner % {'command': sys.argv[0]})
sys.exit(2)
# Replace sys.argv so the script only sees the intended arguments.
sys.argv = original_args
mainpyfile = original_args[0] # Get script filename
if not os.path.exists(mainpyfile):
print 'Error:', mainpyfile, 'does not exist'
sys.exit(1)
# Replace pdb's dir with script's dir in front of module search path.
sys.path[0] = os.path.dirname(mainpyfile)
# Note on saving/restoring sys.argv: it's a good idea when sys.argv was
# modified by the script being debugged. It's a bad idea when it was
# changed by the user from the command line. There is a "restart" command
# which allows explicit specification of command line arguments.
pdb = Pdb()
while True:
for bp in breakpoints:
pdb.do_break(bp)
try:
pdb._runscript(mainpyfile)
if pdb._user_requested_quit:
break
print "The program finished and will be restarted"
except Restart:
print "Restarting", mainpyfile, "with arguments:"
print "\t" + " ".join(original_args[1:])
except SystemExit:
# In most cases SystemExit does not warrant a post-mortem session.
print "The program exited via sys.exit(). Exit status: ",
print sys.exc_info()[1]
except:
traceback.print_exc()
print "Uncaught exception. Entering post mortem debugging"
print "Running 'cont' or 'step' will restart the program"
t = sys.exc_info()[2]
pdb.interaction(None, t)
print "Post mortem debugger finished. The " + mainpyfile + \
" will be restarted"
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment