我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pdb.main()。
def _runscript(self, filename): # The script has to run in __main__ namespace (or imports from # __main__ will break). # # So we clear up the __main__ and set several special variables # (this gets rid of pdb's globals and cleans old variables on restarts). import __main__ __main__.__dict__.clear() __main__.__dict__.update({"__name__" : "__main__", "__file__" : filename, "__builtins__": __builtins__, }) # When bdb sets tracing, a number of call and line events happens # BEFORE debugger even reaches user's code (and the exact sequence of # events depends on python version). So we take special measures to # avoid stopping before we reach the main script (see user_line and # user_call for details). self._wait_for_mainpyfile = 1 self.mainpyfile = self.canonic(filename) self._user_requested_quit = 0 statement = 'execfile(%r)' % filename self.run(statement) # Simplified interface
def main(): '''Run module as a script Uses :py:func:`pdb.main` function directly, but prior to that it mocks :py:class:`pdb.Pdb` class with powerline-specific class instance. ''' orig_pdb = pdb.Pdb @use_powerline_prompt class Pdb(pdb.Pdb, object): def __init__(self): orig_pdb.__init__(self) pdb.Pdb = Pdb return pdb.main()
def run_with_pdb(cmd, *args, **kwargs): # Stolen from pdb.main pdb_context = pdb.Pdb() try: ret = pdb_context.runcall(cmd, **kwargs) print("The program finished") return ret except pdb.Restart: print("Restarting %s with arguments: %s, %s" % (cmd.__name__, args, kwargs)) # Yes, that's a hack return run_with_pdb(cmd, *args, **kwargs) except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. print("The program exited via sys.exit(). Exit status:", end=' ') print(sys.exc_info()[1]) except SyntaxError: traceback.print_exc() sys.exit(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_context.interaction(None, t) print("Post mortem debugger finished.")
def do_continue(self, arg): """c(ont(inue)) Continue execution, only stop when a breakpoint is encountered. """ if not self.nosigint: try: self._previous_sigint_handler = \ signal.signal(signal.SIGINT, self.sigint_handler) except ValueError: # ValueError happens when do_continue() is invoked from # a non-main thread in which case we just continue without # SIGINT set. Would printing a message here (once) make # sense? pass self.set_continue() return 1
def do_run(self, arg): """Restart program by raising an exception to be caught in the main debugger loop. If arguments were given, set them in sys.argv.""" if arg: import shlex argv0 = sys.argv[0:1] sys.argv = shlex.split(arg) sys.argv[:0] = argv0 raise Restart
def do_run(self, arg): """run [args...] Restart the debugged python program. If a string is supplied it is splitted with "shlex", and the result is used as the new sys.argv. History, breakpoints, actions and debugger options are preserved. "restart" is an alias for "run". """ if arg: import shlex argv0 = sys.argv[0:1] sys.argv = shlex.split(arg) sys.argv[:0] = argv0 # this is caught in the main debugger loop raise Restart
def _runscript(self, filename): # The script has to run in __main__ namespace (or imports from # __main__ will break). # # So we clear up the __main__ and set several special variables # (this gets rid of pdb's globals and cleans old variables on restarts). import __main__ __main__.__dict__.clear() __main__.__dict__.update({"__name__" : "__main__", "__file__" : filename, "__builtins__": __builtins__, }) # When bdb sets tracing, a number of call and line events happens # BEFORE debugger even reaches user's code (and the exact sequence of # events depends on python version). So we take special measures to # avoid stopping before we reach the main script (see user_line and # user_call for details). self._wait_for_mainpyfile = True self.mainpyfile = self.canonic(filename) self._user_requested_quit = False with open(filename, "rb") as fp: statement = "exec(compile(%r, %r, 'exec'))" % \ (fp.read(), self.mainpyfile) self.run(statement) # Collect all command help into docstring, if not run with -OO
def do_run(self, arg): """run [args...] Restart the debugged python program. If a string is supplied it is split with "shlex", and the result is used as the new sys.argv. History, breakpoints, actions and debugger options are preserved. "restart" is an alias for "run". """ if arg: import shlex argv0 = sys.argv[0:1] sys.argv = shlex.split(arg) sys.argv[:0] = argv0 # this is caught in the main debugger loop raise Restart
def __init__(self, threading_support=False, *args, **kwargs): ''' Optional arguments: threading_support - Support the threading module and patch a bug preventing catching exceptions in other threads. See add_threading_excepthook for more info. Only neccesary if you want to catch exceptions not on the main thread. This is only patched after __enter__ unpatched at __exit__ All other args from db_stop_if_error()''' self.threading_support=threading_support super(DbStopIfError, self).__init__(*args, **kwargs) #This is all needed JUST for threading. It uses syshook instead of __exit__
def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('--pid', '-p', type=int, default=None) db = parser.add_mutually_exclusive_group(required=False) db.add_argument('--rpdb2', '-r', default=False, action='store_true', help='Attach using rpdb2') db.add_argument('--rpdb', default=False, action='store_true', help='Attach using rpdb (Client not implemented, use putty)') db.add_argument('--winpdb', '--gui', '-g', default=False, action='store_true', help='Attach using winpdb') parser.add_argument('--ip', default='127.0.0.1', help='Set ip address for rpdb/rpdb2/winpdb to attach on') parser.add_argument('--port', default=4444, type=int, help='Set port for rpdb to attach on') parser.add_argument('--password', '--pw', default='vsi') parser.add_argument('args', nargs='*', help='Command to run with vdb attached. Not implemented yet') args = parser.parse_args() if args.pid: #attach to a pid if args.rpdb2 or args.winpdb: from .vdb_rpdb2 import attach as rpdb2_attach rpdb2_attach(args.pid, password=args.password, ip=args.ip, gui=args.winpdb) elif args.rpdb: from .vdb_rpdb import attach as rpdb_attach rpdb_attach(args.pid, ip=args.ip, port=args.port) else: attach(args.pid) else: pass #Do whatever pdb does to run the command #Copy pdb.main or ipdb.main
def main(): if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"): print "usage: pdb.py scriptfile [arg] ..." sys.exit(2) mainpyfile = sys.argv[1] # Get script filename if not os.path.exists(mainpyfile): print 'Error:', mainpyfile, 'does not exist' sys.exit(1) del sys.argv[0] # Hide "pdb.py" from argument list # 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: 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(sys.argv[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" # When invoked as main program, invoke the debugger on a script
def main(): if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"): print "usage: pdb.py scriptfile [arg] ..." sys.exit(2) mainpyfile = sys.argv[1] # Get script filename if not os.path.exists(mainpyfile): print 'Error:', mainpyfile, 'does not exist' sys.exit(1) del sys.argv[0] # Hide "pdb.py" from argument list # 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: 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(sys.argv[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 SyntaxError: traceback.print_exc() sys.exit(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" # When invoked as main program, invoke the debugger on a script
def main(): import getopt opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command=']) if not args: print(_usage) sys.exit(2) commands = [] for opt, optarg in opts: if opt in ['-h', '--help']: print(_usage) sys.exit() elif opt in ['-c', '--command']: commands.append(optarg) mainpyfile = args[0] # Get script filename if not os.path.exists(mainpyfile): print('Error:', mainpyfile, 'does not exist') sys.exit(1) sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list # 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() pdb.rcLines.extend(commands) while True: 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(args)) except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. print("The program exited via sys.exit(). Exit status:", end=' ') 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") # When invoked as main program, invoke the debugger on a script