1#! /usr/bin/env python3 2 3""" 4The Python Debugger Pdb 5======================= 6 7To use the debugger in its simplest form: 8 9 >>> import pdb 10 >>> pdb.run('<a statement>') 11 12The debugger's prompt is '(Pdb) '. This will stop in the first 13function call in <a statement>. 14 15Alternatively, if a statement terminated with an unhandled exception, 16you can use pdb's post-mortem facility to inspect the contents of the 17traceback: 18 19 >>> <a statement> 20 <exception traceback> 21 >>> import pdb 22 >>> pdb.pm() 23 24The commands recognized by the debugger are listed in the next 25section. Most can be abbreviated as indicated; e.g., h(elp) means 26that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel', 27nor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in 28square brackets. Alternatives in the command syntax are separated 29by a vertical bar (|). 30 31A blank line repeats the previous command literally, except for 32'list', where it lists the next 11 lines. 33 34Commands that the debugger doesn't recognize are assumed to be Python 35statements and are executed in the context of the program being 36debugged. Python statements can also be prefixed with an exclamation 37point ('!'). This is a powerful way to inspect the program being 38debugged; it is even possible to change variables or call functions. 39When an exception occurs in such a statement, the exception name is 40printed but the debugger's state is not changed. 41 42The debugger supports aliases, which can save typing. And aliases can 43have parameters (see the alias help entry) which allows one a certain 44level of adaptability to the context under examination. 45 46Multiple commands may be entered on a single line, separated by the 47pair ';;'. No intelligence is applied to separating the commands; the 48input is split at the first ';;', even if it is in the middle of a 49quoted string. 50 51If a file ".pdbrc" exists in your home directory or in the current 52directory, it is read in and executed as if it had been typed at the 53debugger prompt. This is particularly useful for aliases. If both 54files exist, the one in the home directory is read first and aliases 55defined there can be overridden by the local file. This behavior can be 56disabled by passing the "readrc=False" argument to the Pdb constructor. 57 58Aside from aliases, the debugger is not directly programmable; but it 59is implemented as a class from which you can derive your own debugger 60class, which you can make as fancy as you like. 61 62 63Debugger commands 64================= 65 66""" 67# NOTE: the actual command documentation is collected from docstrings of the 68# commands and is appended to __doc__ after the class has been defined. 69 70import os 71import re 72import sys 73import cmd 74import bdb 75import dis 76import code 77import glob 78import pprint 79import signal 80import inspect 81import traceback 82import linecache 83 84 85class Restart(Exception): 86 """Causes a debugger to be restarted for the debugged python program.""" 87 pass 88 89__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace", 90 "post_mortem", "help"] 91 92def find_function(funcname, filename): 93 cre = re.compile(r'def\s+%s\s*[(]' % re.escape(funcname)) 94 try: 95 fp = open(filename) 96 except OSError: 97 return None 98 # consumer of this info expects the first line to be 1 99 with fp: 100 for lineno, line in enumerate(fp, start=1): 101 if cre.match(line): 102 return funcname, filename, lineno 103 return None 104 105def getsourcelines(obj): 106 lines, lineno = inspect.findsource(obj) 107 if inspect.isframe(obj) and obj.f_globals is obj.f_locals: 108 # must be a module frame: do not try to cut a block out of it 109 return lines, 1 110 elif inspect.ismodule(obj): 111 return lines, 1 112 return inspect.getblock(lines[lineno:]), lineno+1 113 114def lasti2lineno(code, lasti): 115 linestarts = list(dis.findlinestarts(code)) 116 linestarts.reverse() 117 for i, lineno in linestarts: 118 if lasti >= i: 119 return lineno 120 return 0 121 122 123class _rstr(str): 124 """String that doesn't quote its repr.""" 125 def __repr__(self): 126 return self 127 128 129# Interaction prompt line will separate file and call info from code 130# text using value of line_prefix string. A newline and arrow may 131# be to your liking. You can set it once pdb is imported using the 132# command "pdb.line_prefix = '\n% '". 133# line_prefix = ': ' # Use this to get the old situation back 134line_prefix = '\n-> ' # Probably a better default 135 136class Pdb(bdb.Bdb, cmd.Cmd): 137 138 _previous_sigint_handler = None 139 140 def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None, 141 nosigint=False, readrc=True): 142 bdb.Bdb.__init__(self, skip=skip) 143 cmd.Cmd.__init__(self, completekey, stdin, stdout) 144 if stdout: 145 self.use_rawinput = 0 146 self.prompt = '(Pdb) ' 147 self.aliases = {} 148 self.displaying = {} 149 self.mainpyfile = '' 150 self._wait_for_mainpyfile = False 151 self.tb_lineno = {} 152 # Try to load readline if it exists 153 try: 154 import readline 155 # remove some common file name delimiters 156 readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?') 157 except ImportError: 158 pass 159 self.allow_kbdint = False 160 self.nosigint = nosigint 161 162 # Read $HOME/.pdbrc and ./.pdbrc 163 self.rcLines = [] 164 if readrc: 165 if 'HOME' in os.environ: 166 envHome = os.environ['HOME'] 167 try: 168 with open(os.path.join(envHome, ".pdbrc")) as rcFile: 169 self.rcLines.extend(rcFile) 170 except OSError: 171 pass 172 try: 173 with open(".pdbrc") as rcFile: 174 self.rcLines.extend(rcFile) 175 except OSError: 176 pass 177 178 self.commands = {} # associates a command list to breakpoint numbers 179 self.commands_doprompt = {} # for each bp num, tells if the prompt 180 # must be disp. after execing the cmd list 181 self.commands_silent = {} # for each bp num, tells if the stack trace 182 # must be disp. after execing the cmd list 183 self.commands_defining = False # True while in the process of defining 184 # a command list 185 self.commands_bnum = None # The breakpoint number for which we are 186 # defining a list 187 188 def sigint_handler(self, signum, frame): 189 if self.allow_kbdint: 190 raise KeyboardInterrupt 191 self.message("\nProgram interrupted. (Use 'cont' to resume).") 192 self.set_step() 193 self.set_trace(frame) 194 195 def reset(self): 196 bdb.Bdb.reset(self) 197 self.forget() 198 199 def forget(self): 200 self.lineno = None 201 self.stack = [] 202 self.curindex = 0 203 self.curframe = None 204 self.tb_lineno.clear() 205 206 def setup(self, f, tb): 207 self.forget() 208 self.stack, self.curindex = self.get_stack(f, tb) 209 while tb: 210 # when setting up post-mortem debugging with a traceback, save all 211 # the original line numbers to be displayed along the current line 212 # numbers (which can be different, e.g. due to finally clauses) 213 lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti) 214 self.tb_lineno[tb.tb_frame] = lineno 215 tb = tb.tb_next 216 self.curframe = self.stack[self.curindex][0] 217 # The f_locals dictionary is updated from the actual frame 218 # locals whenever the .f_locals accessor is called, so we 219 # cache it here to ensure that modifications are not overwritten. 220 self.curframe_locals = self.curframe.f_locals 221 return self.execRcLines() 222 223 # Can be executed earlier than 'setup' if desired 224 def execRcLines(self): 225 if not self.rcLines: 226 return 227 # local copy because of recursion 228 rcLines = self.rcLines 229 rcLines.reverse() 230 # execute every line only once 231 self.rcLines = [] 232 while rcLines: 233 line = rcLines.pop().strip() 234 if line and line[0] != '#': 235 if self.onecmd(line): 236 # if onecmd returns True, the command wants to exit 237 # from the interaction, save leftover rc lines 238 # to execute before next interaction 239 self.rcLines += reversed(rcLines) 240 return True 241 242 # Override Bdb methods 243 244 def user_call(self, frame, argument_list): 245 """This method is called when there is the remote possibility 246 that we ever need to stop in this function.""" 247 if self._wait_for_mainpyfile: 248 return 249 if self.stop_here(frame): 250 self.message('--Call--') 251 self.interaction(frame, None) 252 253 def user_line(self, frame): 254 """This function is called when we stop or break at this line.""" 255 if self._wait_for_mainpyfile: 256 if (self.mainpyfile != self.canonic(frame.f_code.co_filename) 257 or frame.f_lineno <= 0): 258 return 259 self._wait_for_mainpyfile = False 260 if self.bp_commands(frame): 261 self.interaction(frame, None) 262 263 def bp_commands(self, frame): 264 """Call every command that was set for the current active breakpoint 265 (if there is one). 266 267 Returns True if the normal interaction function must be called, 268 False otherwise.""" 269 # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit 270 if getattr(self, "currentbp", False) and \ 271 self.currentbp in self.commands: 272 currentbp = self.currentbp 273 self.currentbp = 0 274 lastcmd_back = self.lastcmd 275 self.setup(frame, None) 276 for line in self.commands[currentbp]: 277 self.onecmd(line) 278 self.lastcmd = lastcmd_back 279 if not self.commands_silent[currentbp]: 280 self.print_stack_entry(self.stack[self.curindex]) 281 if self.commands_doprompt[currentbp]: 282 self._cmdloop() 283 self.forget() 284 return 285 return 1 286 287 def user_return(self, frame, return_value): 288 """This function is called when a return trap is set here.""" 289 if self._wait_for_mainpyfile: 290 return 291 frame.f_locals['__return__'] = return_value 292 self.message('--Return--') 293 self.interaction(frame, None) 294 295 def user_exception(self, frame, exc_info): 296 """This function is called if an exception occurs, 297 but only if we are to stop at or just below this level.""" 298 if self._wait_for_mainpyfile: 299 return 300 exc_type, exc_value, exc_traceback = exc_info 301 frame.f_locals['__exception__'] = exc_type, exc_value 302 303 # An 'Internal StopIteration' exception is an exception debug event 304 # issued by the interpreter when handling a subgenerator run with 305 # 'yield from' or a generator controlled by a for loop. No exception has 306 # actually occurred in this case. The debugger uses this debug event to 307 # stop when the debuggee is returning from such generators. 308 prefix = 'Internal ' if (not exc_traceback 309 and exc_type is StopIteration) else '' 310 self.message('%s%s' % (prefix, 311 traceback.format_exception_only(exc_type, exc_value)[-1].strip())) 312 self.interaction(frame, exc_traceback) 313 314 # General interaction function 315 def _cmdloop(self): 316 while True: 317 try: 318 # keyboard interrupts allow for an easy way to cancel 319 # the current command, so allow them during interactive input 320 self.allow_kbdint = True 321 self.cmdloop() 322 self.allow_kbdint = False 323 break 324 except KeyboardInterrupt: 325 self.message('--KeyboardInterrupt--') 326 327 # Called before loop, handles display expressions 328 def preloop(self): 329 displaying = self.displaying.get(self.curframe) 330 if displaying: 331 for expr, oldvalue in displaying.items(): 332 newvalue = self._getval_except(expr) 333 # check for identity first; this prevents custom __eq__ to 334 # be called at every loop, and also prevents instances whose 335 # fields are changed to be displayed 336 if newvalue is not oldvalue and newvalue != oldvalue: 337 displaying[expr] = newvalue 338 self.message('display %s: %r [old: %r]' % 339 (expr, newvalue, oldvalue)) 340 341 def interaction(self, frame, traceback): 342 # Restore the previous signal handler at the Pdb prompt. 343 if Pdb._previous_sigint_handler: 344 signal.signal(signal.SIGINT, Pdb._previous_sigint_handler) 345 Pdb._previous_sigint_handler = None 346 if self.setup(frame, traceback): 347 # no interaction desired at this time (happens if .pdbrc contains 348 # a command like "continue") 349 self.forget() 350 return 351 self.print_stack_entry(self.stack[self.curindex]) 352 self._cmdloop() 353 self.forget() 354 355 def displayhook(self, obj): 356 """Custom displayhook for the exec in default(), which prevents 357 assignment of the _ variable in the builtins. 358 """ 359 # reproduce the behavior of the standard displayhook, not printing None 360 if obj is not None: 361 self.message(repr(obj)) 362 363 def default(self, line): 364 if line[:1] == '!': line = line[1:] 365 locals = self.curframe_locals 366 globals = self.curframe.f_globals 367 try: 368 code = compile(line + '\n', '<stdin>', 'single') 369 save_stdout = sys.stdout 370 save_stdin = sys.stdin 371 save_displayhook = sys.displayhook 372 try: 373 sys.stdin = self.stdin 374 sys.stdout = self.stdout 375 sys.displayhook = self.displayhook 376 exec(code, globals, locals) 377 finally: 378 sys.stdout = save_stdout 379 sys.stdin = save_stdin 380 sys.displayhook = save_displayhook 381 except: 382 exc_info = sys.exc_info()[:2] 383 self.error(traceback.format_exception_only(*exc_info)[-1].strip()) 384 385 def precmd(self, line): 386 """Handle alias expansion and ';;' separator.""" 387 if not line.strip(): 388 return line 389 args = line.split() 390 while args[0] in self.aliases: 391 line = self.aliases[args[0]] 392 ii = 1 393 for tmpArg in args[1:]: 394 line = line.replace("%" + str(ii), 395 tmpArg) 396 ii += 1 397 line = line.replace("%*", ' '.join(args[1:])) 398 args = line.split() 399 # split into ';;' separated commands 400 # unless it's an alias command 401 if args[0] != 'alias': 402 marker = line.find(';;') 403 if marker >= 0: 404 # queue up everything after marker 405 next = line[marker+2:].lstrip() 406 self.cmdqueue.append(next) 407 line = line[:marker].rstrip() 408 return line 409 410 def onecmd(self, line): 411 """Interpret the argument as though it had been typed in response 412 to the prompt. 413 414 Checks whether this line is typed at the normal prompt or in 415 a breakpoint command list definition. 416 """ 417 if not self.commands_defining: 418 return cmd.Cmd.onecmd(self, line) 419 else: 420 return self.handle_command_def(line) 421 422 def handle_command_def(self, line): 423 """Handles one command line during command list definition.""" 424 cmd, arg, line = self.parseline(line) 425 if not cmd: 426 return 427 if cmd == 'silent': 428 self.commands_silent[self.commands_bnum] = True 429 return # continue to handle other cmd def in the cmd list 430 elif cmd == 'end': 431 self.cmdqueue = [] 432 return 1 # end of cmd list 433 cmdlist = self.commands[self.commands_bnum] 434 if arg: 435 cmdlist.append(cmd+' '+arg) 436 else: 437 cmdlist.append(cmd) 438 # Determine if we must stop 439 try: 440 func = getattr(self, 'do_' + cmd) 441 except AttributeError: 442 func = self.default 443 # one of the resuming commands 444 if func.__name__ in self.commands_resuming: 445 self.commands_doprompt[self.commands_bnum] = False 446 self.cmdqueue = [] 447 return 1 448 return 449 450 # interface abstraction functions 451 452 def message(self, msg): 453 print(msg, file=self.stdout) 454 455 def error(self, msg): 456 print('***', msg, file=self.stdout) 457 458 # Generic completion functions. Individual complete_foo methods can be 459 # assigned below to one of these functions. 460 461 def _complete_location(self, text, line, begidx, endidx): 462 # Complete a file/module/function location for break/tbreak/clear. 463 if line.strip().endswith((':', ',')): 464 # Here comes a line number or a condition which we can't complete. 465 return [] 466 # First, try to find matching functions (i.e. expressions). 467 try: 468 ret = self._complete_expression(text, line, begidx, endidx) 469 except Exception: 470 ret = [] 471 # Then, try to complete file names as well. 472 globs = glob.glob(text + '*') 473 for fn in globs: 474 if os.path.isdir(fn): 475 ret.append(fn + '/') 476 elif os.path.isfile(fn) and fn.lower().endswith(('.py', '.pyw')): 477 ret.append(fn + ':') 478 return ret 479 480 def _complete_bpnumber(self, text, line, begidx, endidx): 481 # Complete a breakpoint number. (This would be more helpful if we could 482 # display additional info along with the completions, such as file/line 483 # of the breakpoint.) 484 return [str(i) for i, bp in enumerate(bdb.Breakpoint.bpbynumber) 485 if bp is not None and str(i).startswith(text)] 486 487 def _complete_expression(self, text, line, begidx, endidx): 488 # Complete an arbitrary expression. 489 if not self.curframe: 490 return [] 491 # Collect globals and locals. It is usually not really sensible to also 492 # complete builtins, and they clutter the namespace quite heavily, so we 493 # leave them out. 494 ns = self.curframe.f_globals.copy() 495 ns.update(self.curframe_locals) 496 if '.' in text: 497 # Walk an attribute chain up to the last part, similar to what 498 # rlcompleter does. This will bail if any of the parts are not 499 # simple attribute access, which is what we want. 500 dotted = text.split('.') 501 try: 502 obj = ns[dotted[0]] 503 for part in dotted[1:-1]: 504 obj = getattr(obj, part) 505 except (KeyError, AttributeError): 506 return [] 507 prefix = '.'.join(dotted[:-1]) + '.' 508 return [prefix + n for n in dir(obj) if n.startswith(dotted[-1])] 509 else: 510 # Complete a simple name. 511 return [n for n in ns.keys() if n.startswith(text)] 512 513 # Command definitions, called by cmdloop() 514 # The argument is the remaining string on the command line 515 # Return true to exit from the command loop 516 517 def do_commands(self, arg): 518 """commands [bpnumber] 519 (com) ... 520 (com) end 521 (Pdb) 522 523 Specify a list of commands for breakpoint number bpnumber. 524 The commands themselves are entered on the following lines. 525 Type a line containing just 'end' to terminate the commands. 526 The commands are executed when the breakpoint is hit. 527 528 To remove all commands from a breakpoint, type commands and 529 follow it immediately with end; that is, give no commands. 530 531 With no bpnumber argument, commands refers to the last 532 breakpoint set. 533 534 You can use breakpoint commands to start your program up 535 again. Simply use the continue command, or step, or any other 536 command that resumes execution. 537 538 Specifying any command resuming execution (currently continue, 539 step, next, return, jump, quit and their abbreviations) 540 terminates the command list (as if that command was 541 immediately followed by end). This is because any time you 542 resume execution (even with a simple next or step), you may 543 encounter another breakpoint -- which could have its own 544 command list, leading to ambiguities about which list to 545 execute. 546 547 If you use the 'silent' command in the command list, the usual 548 message about stopping at a breakpoint is not printed. This 549 may be desirable for breakpoints that are to print a specific 550 message and then continue. If none of the other commands 551 print anything, you will see no sign that the breakpoint was 552 reached. 553 """ 554 if not arg: 555 bnum = len(bdb.Breakpoint.bpbynumber) - 1 556 else: 557 try: 558 bnum = int(arg) 559 except: 560 self.error("Usage: commands [bnum]\n ...\n end") 561 return 562 self.commands_bnum = bnum 563 # Save old definitions for the case of a keyboard interrupt. 564 if bnum in self.commands: 565 old_command_defs = (self.commands[bnum], 566 self.commands_doprompt[bnum], 567 self.commands_silent[bnum]) 568 else: 569 old_command_defs = None 570 self.commands[bnum] = [] 571 self.commands_doprompt[bnum] = True 572 self.commands_silent[bnum] = False 573 574 prompt_back = self.prompt 575 self.prompt = '(com) ' 576 self.commands_defining = True 577 try: 578 self.cmdloop() 579 except KeyboardInterrupt: 580 # Restore old definitions. 581 if old_command_defs: 582 self.commands[bnum] = old_command_defs[0] 583 self.commands_doprompt[bnum] = old_command_defs[1] 584 self.commands_silent[bnum] = old_command_defs[2] 585 else: 586 del self.commands[bnum] 587 del self.commands_doprompt[bnum] 588 del self.commands_silent[bnum] 589 self.error('command definition aborted, old commands restored') 590 finally: 591 self.commands_defining = False 592 self.prompt = prompt_back 593 594 complete_commands = _complete_bpnumber 595 596 def do_break(self, arg, temporary = 0): 597 """b(reak) [ ([filename:]lineno | function) [, condition] ] 598 Without argument, list all breaks. 599 600 With a line number argument, set a break at this line in the 601 current file. With a function name, set a break at the first 602 executable line of that function. If a second argument is 603 present, it is a string specifying an expression which must 604 evaluate to true before the breakpoint is honored. 605 606 The line number may be prefixed with a filename and a colon, 607 to specify a breakpoint in another file (probably one that 608 hasn't been loaded yet). The file is searched for on 609 sys.path; the .py suffix may be omitted. 610 """ 611 if not arg: 612 if self.breaks: # There's at least one 613 self.message("Num Type Disp Enb Where") 614 for bp in bdb.Breakpoint.bpbynumber: 615 if bp: 616 self.message(bp.bpformat()) 617 return 618 # parse arguments; comma has lowest precedence 619 # and cannot occur in filename 620 filename = None 621 lineno = None 622 cond = None 623 comma = arg.find(',') 624 if comma > 0: 625 # parse stuff after comma: "condition" 626 cond = arg[comma+1:].lstrip() 627 arg = arg[:comma].rstrip() 628 # parse stuff before comma: [filename:]lineno | function 629 colon = arg.rfind(':') 630 funcname = None 631 if colon >= 0: 632 filename = arg[:colon].rstrip() 633 f = self.lookupmodule(filename) 634 if not f: 635 self.error('%r not found from sys.path' % filename) 636 return 637 else: 638 filename = f 639 arg = arg[colon+1:].lstrip() 640 try: 641 lineno = int(arg) 642 except ValueError: 643 self.error('Bad lineno: %s' % arg) 644 return 645 else: 646 # no colon; can be lineno or function 647 try: 648 lineno = int(arg) 649 except ValueError: 650 try: 651 func = eval(arg, 652 self.curframe.f_globals, 653 self.curframe_locals) 654 except: 655 func = arg 656 try: 657 if hasattr(func, '__func__'): 658 func = func.__func__ 659 code = func.__code__ 660 #use co_name to identify the bkpt (function names 661 #could be aliased, but co_name is invariant) 662 funcname = code.co_name 663 lineno = code.co_firstlineno 664 filename = code.co_filename 665 except: 666 # last thing to try 667 (ok, filename, ln) = self.lineinfo(arg) 668 if not ok: 669 self.error('The specified object %r is not a function ' 670 'or was not found along sys.path.' % arg) 671 return 672 funcname = ok # ok contains a function name 673 lineno = int(ln) 674 if not filename: 675 filename = self.defaultFile() 676 # Check for reasonable breakpoint 677 line = self.checkline(filename, lineno) 678 if line: 679 # now set the break point 680 err = self.set_break(filename, line, temporary, cond, funcname) 681 if err: 682 self.error(err) 683 else: 684 bp = self.get_breaks(filename, line)[-1] 685 self.message("Breakpoint %d at %s:%d" % 686 (bp.number, bp.file, bp.line)) 687 688 # To be overridden in derived debuggers 689 def defaultFile(self): 690 """Produce a reasonable default.""" 691 filename = self.curframe.f_code.co_filename 692 if filename == '<string>' and self.mainpyfile: 693 filename = self.mainpyfile 694 return filename 695 696 do_b = do_break 697 698 complete_break = _complete_location 699 complete_b = _complete_location 700 701 def do_tbreak(self, arg): 702 """tbreak [ ([filename:]lineno | function) [, condition] ] 703 Same arguments as break, but sets a temporary breakpoint: it 704 is automatically deleted when first hit. 705 """ 706 self.do_break(arg, 1) 707 708 complete_tbreak = _complete_location 709 710 def lineinfo(self, identifier): 711 failed = (None, None, None) 712 # Input is identifier, may be in single quotes 713 idstring = identifier.split("'") 714 if len(idstring) == 1: 715 # not in single quotes 716 id = idstring[0].strip() 717 elif len(idstring) == 3: 718 # quoted 719 id = idstring[1].strip() 720 else: 721 return failed 722 if id == '': return failed 723 parts = id.split('.') 724 # Protection for derived debuggers 725 if parts[0] == 'self': 726 del parts[0] 727 if len(parts) == 0: 728 return failed 729 # Best first guess at file to look at 730 fname = self.defaultFile() 731 if len(parts) == 1: 732 item = parts[0] 733 else: 734 # More than one part. 735 # First is module, second is method/class 736 f = self.lookupmodule(parts[0]) 737 if f: 738 fname = f 739 item = parts[1] 740 answer = find_function(item, fname) 741 return answer or failed 742 743 def checkline(self, filename, lineno): 744 """Check whether specified line seems to be executable. 745 746 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank 747 line or EOF). Warning: testing is not comprehensive. 748 """ 749 # this method should be callable before starting debugging, so default 750 # to "no globals" if there is no current frame 751 globs = self.curframe.f_globals if hasattr(self, 'curframe') else None 752 line = linecache.getline(filename, lineno, globs) 753 if not line: 754 self.message('End of file') 755 return 0 756 line = line.strip() 757 # Don't allow setting breakpoint at a blank line 758 if (not line or (line[0] == '#') or 759 (line[:3] == '"""') or line[:3] == "'''"): 760 self.error('Blank or comment') 761 return 0 762 return lineno 763 764 def do_enable(self, arg): 765 """enable bpnumber [bpnumber ...] 766 Enables the breakpoints given as a space separated list of 767 breakpoint numbers. 768 """ 769 args = arg.split() 770 for i in args: 771 try: 772 bp = self.get_bpbynumber(i) 773 except ValueError as err: 774 self.error(err) 775 else: 776 bp.enable() 777 self.message('Enabled %s' % bp) 778 779 complete_enable = _complete_bpnumber 780 781 def do_disable(self, arg): 782 """disable bpnumber [bpnumber ...] 783 Disables the breakpoints given as a space separated list of 784 breakpoint numbers. Disabling a breakpoint means it cannot 785 cause the program to stop execution, but unlike clearing a 786 breakpoint, it remains in the list of breakpoints and can be 787 (re-)enabled. 788 """ 789 args = arg.split() 790 for i in args: 791 try: 792 bp = self.get_bpbynumber(i) 793 except ValueError as err: 794 self.error(err) 795 else: 796 bp.disable() 797 self.message('Disabled %s' % bp) 798 799 complete_disable = _complete_bpnumber 800 801 def do_condition(self, arg): 802 """condition bpnumber [condition] 803 Set a new condition for the breakpoint, an expression which 804 must evaluate to true before the breakpoint is honored. If 805 condition is absent, any existing condition is removed; i.e., 806 the breakpoint is made unconditional. 807 """ 808 args = arg.split(' ', 1) 809 try: 810 cond = args[1] 811 except IndexError: 812 cond = None 813 try: 814 bp = self.get_bpbynumber(args[0].strip()) 815 except IndexError: 816 self.error('Breakpoint number expected') 817 except ValueError as err: 818 self.error(err) 819 else: 820 bp.cond = cond 821 if not cond: 822 self.message('Breakpoint %d is now unconditional.' % bp.number) 823 else: 824 self.message('New condition set for breakpoint %d.' % bp.number) 825 826 complete_condition = _complete_bpnumber 827 828 def do_ignore(self, arg): 829 """ignore bpnumber [count] 830 Set the ignore count for the given breakpoint number. If 831 count is omitted, the ignore count is set to 0. A breakpoint 832 becomes active when the ignore count is zero. When non-zero, 833 the count is decremented each time the breakpoint is reached 834 and the breakpoint is not disabled and any associated 835 condition evaluates to true. 836 """ 837 args = arg.split() 838 try: 839 count = int(args[1].strip()) 840 except: 841 count = 0 842 try: 843 bp = self.get_bpbynumber(args[0].strip()) 844 except IndexError: 845 self.error('Breakpoint number expected') 846 except ValueError as err: 847 self.error(err) 848 else: 849 bp.ignore = count 850 if count > 0: 851 if count > 1: 852 countstr = '%d crossings' % count 853 else: 854 countstr = '1 crossing' 855 self.message('Will ignore next %s of breakpoint %d.' % 856 (countstr, bp.number)) 857 else: 858 self.message('Will stop next time breakpoint %d is reached.' 859 % bp.number) 860 861 complete_ignore = _complete_bpnumber 862 863 def do_clear(self, arg): 864 """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]] 865 With a space separated list of breakpoint numbers, clear 866 those breakpoints. Without argument, clear all breaks (but 867 first ask confirmation). With a filename:lineno argument, 868 clear all breaks at that line in that file. 869 """ 870 if not arg: 871 try: 872 reply = input('Clear all breaks? ') 873 except EOFError: 874 reply = 'no' 875 reply = reply.strip().lower() 876 if reply in ('y', 'yes'): 877 bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp] 878 self.clear_all_breaks() 879 for bp in bplist: 880 self.message('Deleted %s' % bp) 881 return 882 if ':' in arg: 883 # Make sure it works for "clear C:\foo\bar.py:12" 884 i = arg.rfind(':') 885 filename = arg[:i] 886 arg = arg[i+1:] 887 try: 888 lineno = int(arg) 889 except ValueError: 890 err = "Invalid line number (%s)" % arg 891 else: 892 bplist = self.get_breaks(filename, lineno) 893 err = self.clear_break(filename, lineno) 894 if err: 895 self.error(err) 896 else: 897 for bp in bplist: 898 self.message('Deleted %s' % bp) 899 return 900 numberlist = arg.split() 901 for i in numberlist: 902 try: 903 bp = self.get_bpbynumber(i) 904 except ValueError as err: 905 self.error(err) 906 else: 907 self.clear_bpbynumber(i) 908 self.message('Deleted %s' % bp) 909 do_cl = do_clear # 'c' is already an abbreviation for 'continue' 910 911 complete_clear = _complete_location 912 complete_cl = _complete_location 913 914 def do_where(self, arg): 915 """w(here) 916 Print a stack trace, with the most recent frame at the bottom. 917 An arrow indicates the "current frame", which determines the 918 context of most commands. 'bt' is an alias for this command. 919 """ 920 self.print_stack_trace() 921 do_w = do_where 922 do_bt = do_where 923 924 def _select_frame(self, number): 925 assert 0 <= number < len(self.stack) 926 self.curindex = number 927 self.curframe = self.stack[self.curindex][0] 928 self.curframe_locals = self.curframe.f_locals 929 self.print_stack_entry(self.stack[self.curindex]) 930 self.lineno = None 931 932 def do_up(self, arg): 933 """u(p) [count] 934 Move the current frame count (default one) levels up in the 935 stack trace (to an older frame). 936 """ 937 if self.curindex == 0: 938 self.error('Oldest frame') 939 return 940 try: 941 count = int(arg or 1) 942 except ValueError: 943 self.error('Invalid frame count (%s)' % arg) 944 return 945 if count < 0: 946 newframe = 0 947 else: 948 newframe = max(0, self.curindex - count) 949 self._select_frame(newframe) 950 do_u = do_up 951 952 def do_down(self, arg): 953 """d(own) [count] 954 Move the current frame count (default one) levels down in the 955 stack trace (to a newer frame). 956 """ 957 if self.curindex + 1 == len(self.stack): 958 self.error('Newest frame') 959 return 960 try: 961 count = int(arg or 1) 962 except ValueError: 963 self.error('Invalid frame count (%s)' % arg) 964 return 965 if count < 0: 966 newframe = len(self.stack) - 1 967 else: 968 newframe = min(len(self.stack) - 1, self.curindex + count) 969 self._select_frame(newframe) 970 do_d = do_down 971 972 def do_until(self, arg): 973 """unt(il) [lineno] 974 Without argument, continue execution until the line with a 975 number greater than the current one is reached. With a line 976 number, continue execution until a line with a number greater 977 or equal to that is reached. In both cases, also stop when 978 the current frame returns. 979 """ 980 if arg: 981 try: 982 lineno = int(arg) 983 except ValueError: 984 self.error('Error in argument: %r' % arg) 985 return 986 if lineno <= self.curframe.f_lineno: 987 self.error('"until" line number is smaller than current ' 988 'line number') 989 return 990 else: 991 lineno = None 992 self.set_until(self.curframe, lineno) 993 return 1 994 do_unt = do_until 995 996 def do_step(self, arg): 997 """s(tep) 998 Execute the current line, stop at the first possible occasion 999 (either in a function that is called or in the current 1000 function). 1001 """ 1002 self.set_step() 1003 return 1 1004 do_s = do_step 1005 1006 def do_next(self, arg): 1007 """n(ext) 1008 Continue execution until the next line in the current function 1009 is reached or it returns. 1010 """ 1011 self.set_next(self.curframe) 1012 return 1 1013 do_n = do_next 1014 1015 def do_run(self, arg): 1016 """run [args...] 1017 Restart the debugged python program. If a string is supplied 1018 it is split with "shlex", and the result is used as the new 1019 sys.argv. History, breakpoints, actions and debugger options 1020 are preserved. "restart" is an alias for "run". 1021 """ 1022 if arg: 1023 import shlex 1024 argv0 = sys.argv[0:1] 1025 sys.argv = shlex.split(arg) 1026 sys.argv[:0] = argv0 1027 # this is caught in the main debugger loop 1028 raise Restart 1029 1030 do_restart = do_run 1031 1032 def do_return(self, arg): 1033 """r(eturn) 1034 Continue execution until the current function returns. 1035 """ 1036 self.set_return(self.curframe) 1037 return 1 1038 do_r = do_return 1039 1040 def do_continue(self, arg): 1041 """c(ont(inue)) 1042 Continue execution, only stop when a breakpoint is encountered. 1043 """ 1044 if not self.nosigint: 1045 try: 1046 Pdb._previous_sigint_handler = \ 1047 signal.signal(signal.SIGINT, self.sigint_handler) 1048 except ValueError: 1049 # ValueError happens when do_continue() is invoked from 1050 # a non-main thread in which case we just continue without 1051 # SIGINT set. Would printing a message here (once) make 1052 # sense? 1053 pass 1054 self.set_continue() 1055 return 1 1056 do_c = do_cont = do_continue 1057 1058 def do_jump(self, arg): 1059 """j(ump) lineno 1060 Set the next line that will be executed. Only available in 1061 the bottom-most frame. This lets you jump back and execute 1062 code again, or jump forward to skip code that you don't want 1063 to run. 1064 1065 It should be noted that not all jumps are allowed -- for 1066 instance it is not possible to jump into the middle of a 1067 for loop or out of a finally clause. 1068 """ 1069 if self.curindex + 1 != len(self.stack): 1070 self.error('You can only jump within the bottom frame') 1071 return 1072 try: 1073 arg = int(arg) 1074 except ValueError: 1075 self.error("The 'jump' command requires a line number") 1076 else: 1077 try: 1078 # Do the jump, fix up our copy of the stack, and display the 1079 # new position 1080 self.curframe.f_lineno = arg 1081 self.stack[self.curindex] = self.stack[self.curindex][0], arg 1082 self.print_stack_entry(self.stack[self.curindex]) 1083 except ValueError as e: 1084 self.error('Jump failed: %s' % e) 1085 do_j = do_jump 1086 1087 def do_debug(self, arg): 1088 """debug code 1089 Enter a recursive debugger that steps through the code 1090 argument (which is an arbitrary expression or statement to be 1091 executed in the current environment). 1092 """ 1093 sys.settrace(None) 1094 globals = self.curframe.f_globals 1095 locals = self.curframe_locals 1096 p = Pdb(self.completekey, self.stdin, self.stdout) 1097 p.prompt = "(%s) " % self.prompt.strip() 1098 self.message("ENTERING RECURSIVE DEBUGGER") 1099 try: 1100 sys.call_tracing(p.run, (arg, globals, locals)) 1101 except Exception: 1102 exc_info = sys.exc_info()[:2] 1103 self.error(traceback.format_exception_only(*exc_info)[-1].strip()) 1104 self.message("LEAVING RECURSIVE DEBUGGER") 1105 sys.settrace(self.trace_dispatch) 1106 self.lastcmd = p.lastcmd 1107 1108 complete_debug = _complete_expression 1109 1110 def do_quit(self, arg): 1111 """q(uit)\nexit 1112 Quit from the debugger. The program being executed is aborted. 1113 """ 1114 self._user_requested_quit = True 1115 self.set_quit() 1116 return 1 1117 1118 do_q = do_quit 1119 do_exit = do_quit 1120 1121 def do_EOF(self, arg): 1122 """EOF 1123 Handles the receipt of EOF as a command. 1124 """ 1125 self.message('') 1126 self._user_requested_quit = True 1127 self.set_quit() 1128 return 1 1129 1130 def do_args(self, arg): 1131 """a(rgs) 1132 Print the argument list of the current function. 1133 """ 1134 co = self.curframe.f_code 1135 dict = self.curframe_locals 1136 n = co.co_argcount 1137 if co.co_flags & 4: n = n+1 1138 if co.co_flags & 8: n = n+1 1139 for i in range(n): 1140 name = co.co_varnames[i] 1141 if name in dict: 1142 self.message('%s = %r' % (name, dict[name])) 1143 else: 1144 self.message('%s = *** undefined ***' % (name,)) 1145 do_a = do_args 1146 1147 def do_retval(self, arg): 1148 """retval 1149 Print the return value for the last return of a function. 1150 """ 1151 if '__return__' in self.curframe_locals: 1152 self.message(repr(self.curframe_locals['__return__'])) 1153 else: 1154 self.error('Not yet returned!') 1155 do_rv = do_retval 1156 1157 def _getval(self, arg): 1158 try: 1159 return eval(arg, self.curframe.f_globals, self.curframe_locals) 1160 except: 1161 exc_info = sys.exc_info()[:2] 1162 self.error(traceback.format_exception_only(*exc_info)[-1].strip()) 1163 raise 1164 1165 def _getval_except(self, arg, frame=None): 1166 try: 1167 if frame is None: 1168 return eval(arg, self.curframe.f_globals, self.curframe_locals) 1169 else: 1170 return eval(arg, frame.f_globals, frame.f_locals) 1171 except: 1172 exc_info = sys.exc_info()[:2] 1173 err = traceback.format_exception_only(*exc_info)[-1].strip() 1174 return _rstr('** raised %s **' % err) 1175 1176 def do_p(self, arg): 1177 """p expression 1178 Print the value of the expression. 1179 """ 1180 try: 1181 self.message(repr(self._getval(arg))) 1182 except: 1183 pass 1184 1185 def do_pp(self, arg): 1186 """pp expression 1187 Pretty-print the value of the expression. 1188 """ 1189 try: 1190 self.message(pprint.pformat(self._getval(arg))) 1191 except: 1192 pass 1193 1194 complete_print = _complete_expression 1195 complete_p = _complete_expression 1196 complete_pp = _complete_expression 1197 1198 def do_list(self, arg): 1199 """l(ist) [first [,last] | .] 1200 1201 List source code for the current file. Without arguments, 1202 list 11 lines around the current line or continue the previous 1203 listing. With . as argument, list 11 lines around the current 1204 line. With one argument, list 11 lines starting at that line. 1205 With two arguments, list the given range; if the second 1206 argument is less than the first, it is a count. 1207 1208 The current line in the current frame is indicated by "->". 1209 If an exception is being debugged, the line where the 1210 exception was originally raised or propagated is indicated by 1211 ">>", if it differs from the current line. 1212 """ 1213 self.lastcmd = 'list' 1214 last = None 1215 if arg and arg != '.': 1216 try: 1217 if ',' in arg: 1218 first, last = arg.split(',') 1219 first = int(first.strip()) 1220 last = int(last.strip()) 1221 if last < first: 1222 # assume it's a count 1223 last = first + last 1224 else: 1225 first = int(arg.strip()) 1226 first = max(1, first - 5) 1227 except ValueError: 1228 self.error('Error in argument: %r' % arg) 1229 return 1230 elif self.lineno is None or arg == '.': 1231 first = max(1, self.curframe.f_lineno - 5) 1232 else: 1233 first = self.lineno + 1 1234 if last is None: 1235 last = first + 10 1236 filename = self.curframe.f_code.co_filename 1237 breaklist = self.get_file_breaks(filename) 1238 try: 1239 lines = linecache.getlines(filename, self.curframe.f_globals) 1240 self._print_lines(lines[first-1:last], first, breaklist, 1241 self.curframe) 1242 self.lineno = min(last, len(lines)) 1243 if len(lines) < last: 1244 self.message('[EOF]') 1245 except KeyboardInterrupt: 1246 pass 1247 do_l = do_list 1248 1249 def do_longlist(self, arg): 1250 """longlist | ll 1251 List the whole source code for the current function or frame. 1252 """ 1253 filename = self.curframe.f_code.co_filename 1254 breaklist = self.get_file_breaks(filename) 1255 try: 1256 lines, lineno = getsourcelines(self.curframe) 1257 except OSError as err: 1258 self.error(err) 1259 return 1260 self._print_lines(lines, lineno, breaklist, self.curframe) 1261 do_ll = do_longlist 1262 1263 def do_source(self, arg): 1264 """source expression 1265 Try to get source code for the given object and display it. 1266 """ 1267 try: 1268 obj = self._getval(arg) 1269 except: 1270 return 1271 try: 1272 lines, lineno = getsourcelines(obj) 1273 except (OSError, TypeError) as err: 1274 self.error(err) 1275 return 1276 self._print_lines(lines, lineno) 1277 1278 complete_source = _complete_expression 1279 1280 def _print_lines(self, lines, start, breaks=(), frame=None): 1281 """Print a range of lines.""" 1282 if frame: 1283 current_lineno = frame.f_lineno 1284 exc_lineno = self.tb_lineno.get(frame, -1) 1285 else: 1286 current_lineno = exc_lineno = -1 1287 for lineno, line in enumerate(lines, start): 1288 s = str(lineno).rjust(3) 1289 if len(s) < 4: 1290 s += ' ' 1291 if lineno in breaks: 1292 s += 'B' 1293 else: 1294 s += ' ' 1295 if lineno == current_lineno: 1296 s += '->' 1297 elif lineno == exc_lineno: 1298 s += '>>' 1299 self.message(s + '\t' + line.rstrip()) 1300 1301 def do_whatis(self, arg): 1302 """whatis arg 1303 Print the type of the argument. 1304 """ 1305 try: 1306 value = self._getval(arg) 1307 except: 1308 # _getval() already printed the error 1309 return 1310 code = None 1311 # Is it a function? 1312 try: 1313 code = value.__code__ 1314 except Exception: 1315 pass 1316 if code: 1317 self.message('Function %s' % code.co_name) 1318 return 1319 # Is it an instance method? 1320 try: 1321 code = value.__func__.__code__ 1322 except Exception: 1323 pass 1324 if code: 1325 self.message('Method %s' % code.co_name) 1326 return 1327 # Is it a class? 1328 if value.__class__ is type: 1329 self.message('Class %s.%s' % (value.__module__, value.__qualname__)) 1330 return 1331 # None of the above... 1332 self.message(type(value)) 1333 1334 complete_whatis = _complete_expression 1335 1336 def do_display(self, arg): 1337 """display [expression] 1338 1339 Display the value of the expression if it changed, each time execution 1340 stops in the current frame. 1341 1342 Without expression, list all display expressions for the current frame. 1343 """ 1344 if not arg: 1345 self.message('Currently displaying:') 1346 for item in self.displaying.get(self.curframe, {}).items(): 1347 self.message('%s: %r' % item) 1348 else: 1349 val = self._getval_except(arg) 1350 self.displaying.setdefault(self.curframe, {})[arg] = val 1351 self.message('display %s: %r' % (arg, val)) 1352 1353 complete_display = _complete_expression 1354 1355 def do_undisplay(self, arg): 1356 """undisplay [expression] 1357 1358 Do not display the expression any more in the current frame. 1359 1360 Without expression, clear all display expressions for the current frame. 1361 """ 1362 if arg: 1363 try: 1364 del self.displaying.get(self.curframe, {})[arg] 1365 except KeyError: 1366 self.error('not displaying %s' % arg) 1367 else: 1368 self.displaying.pop(self.curframe, None) 1369 1370 def complete_undisplay(self, text, line, begidx, endidx): 1371 return [e for e in self.displaying.get(self.curframe, {}) 1372 if e.startswith(text)] 1373 1374 def do_interact(self, arg): 1375 """interact 1376 1377 Start an interactive interpreter whose global namespace 1378 contains all the (global and local) names found in the current scope. 1379 """ 1380 ns = self.curframe.f_globals.copy() 1381 ns.update(self.curframe_locals) 1382 code.interact("*interactive*", local=ns) 1383 1384 def do_alias(self, arg): 1385 """alias [name [command [parameter parameter ...] ]] 1386 Create an alias called 'name' that executes 'command'. The 1387 command must *not* be enclosed in quotes. Replaceable 1388 parameters can be indicated by %1, %2, and so on, while %* is 1389 replaced by all the parameters. If no command is given, the 1390 current alias for name is shown. If no name is given, all 1391 aliases are listed. 1392 1393 Aliases may be nested and can contain anything that can be 1394 legally typed at the pdb prompt. Note! You *can* override 1395 internal pdb commands with aliases! Those internal commands 1396 are then hidden until the alias is removed. Aliasing is 1397 recursively applied to the first word of the command line; all 1398 other words in the line are left alone. 1399 1400 As an example, here are two useful aliases (especially when 1401 placed in the .pdbrc file): 1402 1403 # Print instance variables (usage "pi classInst") 1404 alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k]) 1405 # Print instance variables in self 1406 alias ps pi self 1407 """ 1408 args = arg.split() 1409 if len(args) == 0: 1410 keys = sorted(self.aliases.keys()) 1411 for alias in keys: 1412 self.message("%s = %s" % (alias, self.aliases[alias])) 1413 return 1414 if args[0] in self.aliases and len(args) == 1: 1415 self.message("%s = %s" % (args[0], self.aliases[args[0]])) 1416 else: 1417 self.aliases[args[0]] = ' '.join(args[1:]) 1418 1419 def do_unalias(self, arg): 1420 """unalias name 1421 Delete the specified alias. 1422 """ 1423 args = arg.split() 1424 if len(args) == 0: return 1425 if args[0] in self.aliases: 1426 del self.aliases[args[0]] 1427 1428 def complete_unalias(self, text, line, begidx, endidx): 1429 return [a for a in self.aliases if a.startswith(text)] 1430 1431 # List of all the commands making the program resume execution. 1432 commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return', 1433 'do_quit', 'do_jump'] 1434 1435 # Print a traceback starting at the top stack frame. 1436 # The most recently entered frame is printed last; 1437 # this is different from dbx and gdb, but consistent with 1438 # the Python interpreter's stack trace. 1439 # It is also consistent with the up/down commands (which are 1440 # compatible with dbx and gdb: up moves towards 'main()' 1441 # and down moves towards the most recent stack frame). 1442 1443 def print_stack_trace(self): 1444 try: 1445 for frame_lineno in self.stack: 1446 self.print_stack_entry(frame_lineno) 1447 except KeyboardInterrupt: 1448 pass 1449 1450 def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix): 1451 frame, lineno = frame_lineno 1452 if frame is self.curframe: 1453 prefix = '> ' 1454 else: 1455 prefix = ' ' 1456 self.message(prefix + 1457 self.format_stack_entry(frame_lineno, prompt_prefix)) 1458 1459 # Provide help 1460 1461 def do_help(self, arg): 1462 """h(elp) 1463 Without argument, print the list of available commands. 1464 With a command name as argument, print help about that command. 1465 "help pdb" shows the full pdb documentation. 1466 "help exec" gives help on the ! command. 1467 """ 1468 if not arg: 1469 return cmd.Cmd.do_help(self, arg) 1470 try: 1471 try: 1472 topic = getattr(self, 'help_' + arg) 1473 return topic() 1474 except AttributeError: 1475 command = getattr(self, 'do_' + arg) 1476 except AttributeError: 1477 self.error('No help for %r' % arg) 1478 else: 1479 if sys.flags.optimize >= 2: 1480 self.error('No help for %r; please do not run Python with -OO ' 1481 'if you need command help' % arg) 1482 return 1483 self.message(command.__doc__.rstrip()) 1484 1485 do_h = do_help 1486 1487 def help_exec(self): 1488 """(!) statement 1489 Execute the (one-line) statement in the context of the current 1490 stack frame. The exclamation point can be omitted unless the 1491 first word of the statement resembles a debugger command. To 1492 assign to a global variable you must always prefix the command 1493 with a 'global' command, e.g.: 1494 (Pdb) global list_options; list_options = ['-l'] 1495 (Pdb) 1496 """ 1497 self.message((self.help_exec.__doc__ or '').strip()) 1498 1499 def help_pdb(self): 1500 help() 1501 1502 # other helper functions 1503 1504 def lookupmodule(self, filename): 1505 """Helper function for break/clear parsing -- may be overridden. 1506 1507 lookupmodule() translates (possibly incomplete) file or module name 1508 into an absolute file name. 1509 """ 1510 if os.path.isabs(filename) and os.path.exists(filename): 1511 return filename 1512 f = os.path.join(sys.path[0], filename) 1513 if os.path.exists(f) and self.canonic(f) == self.mainpyfile: 1514 return f 1515 root, ext = os.path.splitext(filename) 1516 if ext == '': 1517 filename = filename + '.py' 1518 if os.path.isabs(filename): 1519 return filename 1520 for dirname in sys.path: 1521 while os.path.islink(dirname): 1522 dirname = os.readlink(dirname) 1523 fullname = os.path.join(dirname, filename) 1524 if os.path.exists(fullname): 1525 return fullname 1526 return None 1527 1528 def _runmodule(self, module_name): 1529 self._wait_for_mainpyfile = True 1530 self._user_requested_quit = False 1531 import runpy 1532 mod_name, mod_spec, code = runpy._get_module_details(module_name) 1533 self.mainpyfile = self.canonic(code.co_filename) 1534 import __main__ 1535 __main__.__dict__.clear() 1536 __main__.__dict__.update({ 1537 "__name__": "__main__", 1538 "__file__": self.mainpyfile, 1539 "__package__": mod_spec.parent, 1540 "__loader__": mod_spec.loader, 1541 "__spec__": mod_spec, 1542 "__builtins__": __builtins__, 1543 }) 1544 self.run(code) 1545 1546 def _runscript(self, filename): 1547 # The script has to run in __main__ namespace (or imports from 1548 # __main__ will break). 1549 # 1550 # So we clear up the __main__ and set several special variables 1551 # (this gets rid of pdb's globals and cleans old variables on restarts). 1552 import __main__ 1553 __main__.__dict__.clear() 1554 __main__.__dict__.update({"__name__" : "__main__", 1555 "__file__" : filename, 1556 "__builtins__": __builtins__, 1557 }) 1558 1559 # When bdb sets tracing, a number of call and line events happens 1560 # BEFORE debugger even reaches user's code (and the exact sequence of 1561 # events depends on python version). So we take special measures to 1562 # avoid stopping before we reach the main script (see user_line and 1563 # user_call for details). 1564 self._wait_for_mainpyfile = True 1565 self.mainpyfile = self.canonic(filename) 1566 self._user_requested_quit = False 1567 with open(filename, "rb") as fp: 1568 statement = "exec(compile(%r, %r, 'exec'))" % \ 1569 (fp.read(), self.mainpyfile) 1570 self.run(statement) 1571 1572# Collect all command help into docstring, if not run with -OO 1573 1574if __doc__ is not None: 1575 # unfortunately we can't guess this order from the class definition 1576 _help_order = [ 1577 'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable', 1578 'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until', 1579 'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist', 1580 'args', 'p', 'pp', 'whatis', 'source', 'display', 'undisplay', 1581 'interact', 'alias', 'unalias', 'debug', 'quit', 1582 ] 1583 1584 for _command in _help_order: 1585 __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n' 1586 __doc__ += Pdb.help_exec.__doc__ 1587 1588 del _help_order, _command 1589 1590 1591# Simplified interface 1592 1593def run(statement, globals=None, locals=None): 1594 Pdb().run(statement, globals, locals) 1595 1596def runeval(expression, globals=None, locals=None): 1597 return Pdb().runeval(expression, globals, locals) 1598 1599def runctx(statement, globals, locals): 1600 # B/W compatibility 1601 run(statement, globals, locals) 1602 1603def runcall(*args, **kwds): 1604 return Pdb().runcall(*args, **kwds) 1605 1606def set_trace(*, header=None): 1607 pdb = Pdb() 1608 if header is not None: 1609 pdb.message(header) 1610 pdb.set_trace(sys._getframe().f_back) 1611 1612# Post-Mortem interface 1613 1614def post_mortem(t=None): 1615 # handling the default 1616 if t is None: 1617 # sys.exc_info() returns (type, value, traceback) if an exception is 1618 # being handled, otherwise it returns None 1619 t = sys.exc_info()[2] 1620 if t is None: 1621 raise ValueError("A valid traceback must be passed if no " 1622 "exception is being handled") 1623 1624 p = Pdb() 1625 p.reset() 1626 p.interaction(None, t) 1627 1628def pm(): 1629 post_mortem(sys.last_traceback) 1630 1631 1632# Main program for testing 1633 1634TESTCMD = 'import x; x.main()' 1635 1636def test(): 1637 run(TESTCMD) 1638 1639# print help 1640def help(): 1641 import pydoc 1642 pydoc.pager(__doc__) 1643 1644_usage = """\ 1645usage: pdb.py [-c command] ... [-m module | pyfile] [arg] ... 1646 1647Debug the Python program given by pyfile. Alternatively, 1648an executable module or package to debug can be specified using 1649the -m switch. 1650 1651Initial commands are read from .pdbrc files in your home directory 1652and in the current directory, if they exist. Commands supplied with 1653-c are executed after commands from .pdbrc files. 1654 1655To let the script run until an exception occurs, use "-c continue". 1656To let the script run up to a given line X in the debugged file, use 1657"-c 'until X'".""" 1658 1659def main(): 1660 import getopt 1661 1662 opts, args = getopt.getopt(sys.argv[1:], 'mhc:', ['--help', '--command=']) 1663 1664 if not args: 1665 print(_usage) 1666 sys.exit(2) 1667 1668 commands = [] 1669 run_as_module = False 1670 for opt, optarg in opts: 1671 if opt in ['-h', '--help']: 1672 print(_usage) 1673 sys.exit() 1674 elif opt in ['-c', '--command']: 1675 commands.append(optarg) 1676 elif opt in ['-m']: 1677 run_as_module = True 1678 1679 mainpyfile = args[0] # Get script filename 1680 if not run_as_module and not os.path.exists(mainpyfile): 1681 print('Error:', mainpyfile, 'does not exist') 1682 sys.exit(1) 1683 1684 sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list 1685 1686 # Replace pdb's dir with script's dir in front of module search path. 1687 if not run_as_module: 1688 sys.path[0] = os.path.dirname(mainpyfile) 1689 1690 # Note on saving/restoring sys.argv: it's a good idea when sys.argv was 1691 # modified by the script being debugged. It's a bad idea when it was 1692 # changed by the user from the command line. There is a "restart" command 1693 # which allows explicit specification of command line arguments. 1694 pdb = Pdb() 1695 pdb.rcLines.extend(commands) 1696 while True: 1697 try: 1698 if run_as_module: 1699 pdb._runmodule(mainpyfile) 1700 else: 1701 pdb._runscript(mainpyfile) 1702 if pdb._user_requested_quit: 1703 break 1704 print("The program finished and will be restarted") 1705 except Restart: 1706 print("Restarting", mainpyfile, "with arguments:") 1707 print("\t" + " ".join(args)) 1708 except SystemExit: 1709 # In most cases SystemExit does not warrant a post-mortem session. 1710 print("The program exited via sys.exit(). Exit status:", end=' ') 1711 print(sys.exc_info()[1]) 1712 except SyntaxError: 1713 traceback.print_exc() 1714 sys.exit(1) 1715 except: 1716 traceback.print_exc() 1717 print("Uncaught exception. Entering post mortem debugging") 1718 print("Running 'cont' or 'step' will restart the program") 1719 t = sys.exc_info()[2] 1720 pdb.interaction(None, t) 1721 print("Post mortem debugger finished. The " + mainpyfile + 1722 " will be restarted") 1723 1724 1725# When invoked as main program, invoke the debugger on a script 1726if __name__ == '__main__': 1727 import pdb 1728 pdb.main() 1729