Debian Codegraph @

lib-python/3/pdb.py

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