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