Debian Codegraph @

Doc/library/pdb.rst

raw
1 .. _debugger:
2
3 :mod:`!pdb` --- The Python Debugger
4 ===================================
5
6 .. module:: pdb
7 :synopsis: The Python debugger for interactive interpreters.
8
9 **Source code:** :source:`Lib/pdb.py`
10
11 .. index:: single: debugging
12
13 --------------
14
15 The module :mod:`!pdb` defines an interactive source code debugger for Python
16 programs. It supports setting (conditional) breakpoints and single stepping at
17 the source line level, inspection of stack frames, source code listing, and
18 evaluation of arbitrary Python code in the context of any stack frame. It also
19 supports post-mortem debugging and can be called under program control.
20
21 .. index::
22 single: Pdb (class in pdb)
23 pair: module; bdb
24 pair: module; cmd
25
26 The debugger is extensible -- it is actually defined as the class :class:`Pdb`.
27 This is currently undocumented but easily understood by reading the source. The
28 extension interface uses the modules :mod:`bdb` and :mod:`cmd`.
29
30 .. seealso::
31
32 Module :mod:`faulthandler`
33 Used to dump Python tracebacks explicitly, on a fault, after a timeout,
34 or on a user signal.
35
36 Module :mod:`traceback`
37 Standard interface to extract, format and print stack traces of Python programs.
38
39 The typical usage to break into the debugger is to insert::
40
41 import pdb; pdb.set_trace()
42
43 Or::
44
45 breakpoint()
46
47 at the location you want to break into the debugger, and then run the program.
48 You can then step through the code following this statement, and continue
49 running without the debugger using the :pdbcmd:`continue` command.
50
51 .. versionchanged:: 3.7
52 The built-in :func:`breakpoint`, when called with defaults, can be used
53 instead of ``import pdb; pdb.set_trace()``.
54
55 ::
56
57 def double(x):
58 breakpoint()
59 return x * 2
60 val = 3
61 print(f"{val} * 2 is {double(val)}")
62
63 The debugger's prompt is ``(Pdb)``, which is the indicator that you are in debug mode::
64
65 > ...(2)double()
66 -> breakpoint()
67 (Pdb) p x
68 3
69 (Pdb) continue
70 3 * 2 is 6
71
72 .. versionchanged:: 3.3
73 Tab-completion via the :mod:`readline` module is available for commands and
74 command arguments, e.g. the current global and local names are offered as
75 arguments of the ``p`` command.
76
77
78 .. _pdb-cli:
79
80 Command-line interface
81 ----------------------
82
83 .. program:: pdb
84
85 You can also invoke :mod:`!pdb` from the command line to debug other scripts. For
86 example::
87
88 python -m pdb [-c command] (-m module | -p pid | pyfile) [args ...]
89
90 When invoked as a module, pdb will automatically enter post-mortem debugging if
91 the program being debugged exits abnormally. After post-mortem debugging (or
92 after normal exit of the program), pdb will restart the program. Automatic
93 restarting preserves pdb's state (such as breakpoints) and in most cases is more
94 useful than quitting the debugger upon program's exit.
95
96 .. option:: -c, --command <command>
97
98 To execute commands as if given in a :file:`.pdbrc` file; see
99 :ref:`debugger-commands`.
100
101 .. versionchanged:: 3.2
102 Added the ``-c`` option.
103
104 .. option:: -m <module>
105
106 To execute modules similar to the way ``python -m`` does. As with a script,
107 the debugger will pause execution just before the first line of the module.
108
109 .. versionchanged:: 3.7
110 Added the ``-m`` option.
111
112 .. option:: -p, --pid <pid>
113
114 Attach to the process with the specified PID.
115
116 .. versionadded:: 3.14
117
118
119 To attach to a running Python process for remote debugging, use the ``-p`` or
120 ``--pid`` option with the target process's PID::
121
122 python -m pdb -p 1234
123
124 .. note::
125
126 Attaching to a process that is blocked in a system call or waiting for I/O
127 will only work once the next bytecode instruction is executed or when the
128 process receives a signal.
129
130 Typical usage to execute a statement under control of the debugger is::
131
132 >>> import pdb
133 >>> def f(x):
134 ... print(1 / x)
135 >>> pdb.run("f(2)")
136 > <string>(1)<module>()
137 (Pdb) continue
138 0.5
139 >>>
140
141 The typical usage to inspect a crashed program is::
142
143 >>> import pdb
144 >>> def f(x):
145 ... print(1 / x)
146 ...
147 >>> f(0)
148 Traceback (most recent call last):
149 File "<stdin>", line 1, in <module>
150 File "<stdin>", line 2, in f
151 ZeroDivisionError: division by zero
152 >>> pdb.pm()
153 > <stdin>(2)f()
154 (Pdb) p x
155 0
156 (Pdb)
157
158 .. versionchanged:: 3.13
159 The implementation of :pep:`667` means that name assignments made via ``pdb``
160 will immediately affect the active scope, even when running inside an
161 :term:`optimized scope`.
162
163
164 The module defines the following functions; each enters the debugger in a
165 slightly different way:
166
167 .. function:: run(statement, globals=None, locals=None)
168
169 Execute the *statement* (given as a string or a code object) under debugger
170 control. The debugger prompt appears before any code is executed; you can
171 set breakpoints and type :pdbcmd:`continue`, or you can step through the
172 statement using :pdbcmd:`step` or :pdbcmd:`next` (all these commands are
173 explained below). The optional *globals* and *locals* arguments specify the
174 environment in which the code is executed; by default the dictionary of the
175 module :mod:`__main__` is used. (See the explanation of the built-in
176 :func:`exec` or :func:`eval` functions.)
177
178
179 .. function:: runeval(expression, globals=None, locals=None)
180
181 Evaluate the *expression* (given as a string or a code object) under debugger
182 control. When :func:`runeval` returns, it returns the value of the
183 *expression*. Otherwise this function is similar to :func:`run`.
184
185
186 .. function:: runcall(function, *args, **kwds)
187
188 Call the *function* (a function or method object, not a string) with the
189 given arguments. When :func:`runcall` returns, it returns whatever the
190 function call returned. The debugger prompt appears as soon as the function
191 is entered.
192
193
194 .. function:: set_trace(*, header=None, commands=None)
195
196 Enter the debugger at the calling stack frame. This is useful to hard-code
197 a breakpoint at a given point in a program, even if the code is not
198 otherwise being debugged (e.g. when an assertion fails). If given,
199 *header* is printed to the console just before debugging begins.
200 The *commands* argument, if given, is a list of commands to execute
201 when the debugger starts.
202
203
204 .. versionchanged:: 3.7
205 The keyword-only argument *header*.
206
207 .. versionchanged:: 3.13
208 :func:`set_trace` will enter the debugger immediately, rather than
209 on the next line of code to be executed.
210
211 .. versionadded:: 3.14
212 The *commands* argument.
213
214
215 .. awaitablefunction:: set_trace_async(*, header=None, commands=None)
216
217 async version of :func:`set_trace`. This function should be used inside an
218 async function with :keyword:`await`.
219
220 .. code-block:: python
221
222 async def f():
223 await pdb.set_trace_async()
224
225 :keyword:`await` statements are supported if the debugger is invoked by this function.
226
227 .. versionadded:: 3.14
228
229 .. function:: post_mortem(t=None)
230
231 Enter post-mortem debugging of the given exception or
232 :ref:`traceback object <traceback-objects>`. If no value is given, it uses
233 the exception that is currently being handled, or raises ``ValueError`` if
234 there isn’t one.
235
236 .. versionchanged:: 3.13
237 Support for exception objects was added.
238
239 .. function:: pm()
240
241 Enter post-mortem debugging of the exception found in
242 :data:`sys.last_exc`.
243
244 .. function:: set_default_backend(backend)
245
246 There are two supported backends for pdb: ``'settrace'`` and ``'monitoring'``.
247 See :class:`bdb.Bdb` for details. The user can set the default backend to
248 use if none is specified when instantiating :class:`Pdb`. If no backend is
249 specified, the default is ``'settrace'``.
250
251 .. note::
252
253 :func:`breakpoint` and :func:`set_trace` will not be affected by this
254 function. They always use ``'monitoring'`` backend.
255
256 .. versionadded:: 3.14
257
258 .. function:: get_default_backend()
259
260 Returns the default backend for pdb.
261
262 .. versionadded:: 3.14
263
264 The ``run*`` functions and :func:`set_trace` are aliases for instantiating the
265 :class:`Pdb` class and calling the method of the same name. If you want to
266 access further features, you have to do this yourself:
267
268 .. class:: Pdb(completekey='tab', stdin=None, stdout=None, skip=None, \
269 nosigint=False, readrc=True, mode=None, backend=None, colorize=False)
270
271 :class:`Pdb` is the debugger class.
272
273 The *completekey*, *stdin* and *stdout* arguments are passed to the
274 underlying :class:`cmd.Cmd` class; see the description there.
275
276 The *skip* argument, if given, must be an iterable of glob-style module name
277 patterns. The debugger will not step into frames that originate in a module
278 that matches one of these patterns. [1]_
279
280 By default, Pdb sets a handler for the SIGINT signal (which is sent when the
281 user presses :kbd:`Ctrl-C` on the console) when you give a :pdbcmd:`continue` command.
282 This allows you to break into the debugger again by pressing :kbd:`Ctrl-C`. If you
283 want Pdb not to touch the SIGINT handler, set *nosigint* to true.
284
285 The *readrc* argument defaults to true and controls whether Pdb will load
286 .pdbrc files from the filesystem.
287
288 The *mode* argument specifies how the debugger was invoked.
289 It impacts the workings of some debugger commands.
290 Valid values are ``'inline'`` (used by the breakpoint() builtin),
291 ``'cli'`` (used by the command line invocation)
292 or ``None`` (for backwards compatible behaviour, as before the *mode*
293 argument was added).
294
295 The *backend* argument specifies the backend to use for the debugger. If ``None``
296 is passed, the default backend will be used. See :func:`set_default_backend`.
297 Otherwise the supported backends are ``'settrace'`` and ``'monitoring'``.
298
299 The *colorize* argument, if set to ``True``, will enable colorized output in the
300 debugger, if color is supported. This will highlight source code displayed in pdb.
301
302 Example call to enable tracing with *skip*::
303
304 import pdb; pdb.Pdb(skip=['django.*']).set_trace()
305
306 .. audit-event:: pdb.Pdb "" pdb.Pdb
307
308 .. versionchanged:: 3.1
309 Added the *skip* parameter.
310
311 .. versionchanged:: 3.2
312 Added the *nosigint* parameter.
313 Previously, a SIGINT handler was never set by Pdb.
314
315 .. versionchanged:: 3.6
316 The *readrc* argument.
317
318 .. versionadded:: 3.14
319 Added the *mode* argument.
320
321 .. versionadded:: 3.14
322 Added the *backend* argument.
323
324 .. versionadded:: 3.14
325 Added the *colorize* argument.
326
327 .. versionchanged:: 3.14
328 Inline breakpoints like :func:`breakpoint` or :func:`pdb.set_trace` will
329 always stop the program at calling frame, ignoring the *skip* pattern (if any).
330
331 .. method:: run(statement, globals=None, locals=None)
332 runeval(expression, globals=None, locals=None)
333 runcall(function, *args, **kwds)
334 set_trace()
335
336 See the documentation for the functions explained above.
337
338
339 .. _debugger-commands:
340
341 Debugger commands
342 -----------------
343
344 The commands recognized by the debugger are listed below. Most commands can be
345 abbreviated to one or two letters as indicated; e.g. ``h(elp)`` means that
346 either ``h`` or ``help`` can be used to enter the help command (but not ``he``
347 or ``hel``, nor ``H`` or ``Help`` or ``HELP``). Arguments to commands must be
348 separated by whitespace (spaces or tabs). Optional arguments are enclosed in
349 square brackets (``[]``) in the command syntax; the square brackets must not be
350 typed. Alternatives in the command syntax are separated by a vertical bar
351 (``|``).
352
353 Entering a blank line repeats the last command entered. Exception: if the last
354 command was a :pdbcmd:`list` command, the next 11 lines are listed.
355
356 Commands that the debugger doesn't recognize are assumed to be Python statements
357 and are executed in the context of the program being debugged. Python
358 statements can also be prefixed with an exclamation point (``!``). This is a
359 powerful way to inspect the program being debugged; it is even possible to
360 change a variable or call a function. When an exception occurs in such a
361 statement, the exception name is printed but the debugger's state is not
362 changed.
363
364 .. versionchanged:: 3.13
365 Expressions/Statements whose prefix is a pdb command are now correctly
366 identified and executed.
367
368 The debugger supports :ref:`aliases <debugger-aliases>`. Aliases can have
369 parameters which allows one a certain level of adaptability to the context under
370 examination.
371
372 Multiple commands may be entered on a single line, separated by ``;;``. (A
373 single ``;`` is not used as it is the separator for multiple commands in a line
374 that is passed to the Python parser.) No intelligence is applied to separating
375 the commands; the input is split at the first ``;;`` pair, even if it is in the
376 middle of a quoted string. A workaround for strings with double semicolons
377 is to use implicit string concatenation ``';'';'`` or ``";"";"``.
378
379 To set a temporary global variable, use a *convenience variable*. A *convenience
380 variable* is a variable whose name starts with ``$``. For example, ``$foo = 1``
381 sets a global variable ``$foo`` which you can use in the debugger session. The
382 *convenience variables* are cleared when the program resumes execution so it's
383 less likely to interfere with your program compared to using normal variables
384 like ``foo = 1``.
385
386 There are four preset *convenience variables*:
387
388 * ``$_frame``: the current frame you are debugging
389 * ``$_retval``: the return value if the frame is returning
390 * ``$_exception``: the exception if the frame is raising an exception
391 * ``$_asynctask``: the asyncio task if pdb stops in an async function
392
393 .. versionadded:: 3.12
394
395 Added the *convenience variable* feature.
396
397 .. versionadded:: 3.14
398 Added the ``$_asynctask`` convenience variable.
399
400 .. index::
401 pair: .pdbrc; file
402 triple: debugger; configuration; file
403
404 If a file :file:`.pdbrc` exists in the user's home directory or in the current
405 directory, it is read with ``'utf-8'`` encoding and executed as if it had been
406 typed at the debugger prompt, with the exception that empty lines and lines
407 starting with ``#`` are ignored. This is particularly useful for aliases. If both
408 files exist, the one in the home directory is read first and aliases defined there
409 can be overridden by the local file.
410
411 .. versionchanged:: 3.2
412 :file:`.pdbrc` can now contain commands that continue debugging, such as
413 :pdbcmd:`continue` or :pdbcmd:`next`. Previously, these commands had no
414 effect.
415
416 .. versionchanged:: 3.11
417 :file:`.pdbrc` is now read with ``'utf-8'`` encoding. Previously, it was read
418 with the system locale encoding.
419
420
421 .. pdbcommand:: h(elp) [command]
422
423 Without argument, print the list of available commands. With a *command* as
424 argument, print help about that command. ``help pdb`` displays the full
425 documentation (the docstring of the :mod:`pdb` module). Since the *command*
426 argument must be an identifier, ``help exec`` must be entered to get help on
427 the ``!`` command.
428
429 .. pdbcommand:: w(here) [count]
430
431 Print a stack trace, with the most recent frame at the bottom. if *count*
432 is 0, print the current frame entry. If *count* is negative, print the least
433 recent - *count* frames. If *count* is positive, print the most recent
434 *count* frames. An arrow (``>``)
435 indicates the current frame, which determines the context of most commands.
436
437 .. versionchanged:: 3.14
438 *count* argument is added.
439
440 .. pdbcommand:: d(own) [count]
441
442 Move the current frame *count* (default one) levels down in the stack trace
443 (to a newer frame).
444
445 .. pdbcommand:: u(p) [count]
446
447 Move the current frame *count* (default one) levels up in the stack trace (to
448 an older frame).
449
450 .. pdbcommand:: b(reak) [([filename:]lineno | function) [, condition]]
451
452 With a *lineno* argument, set a break at line *lineno* in the current file.
453 The line number may be prefixed with a *filename* and a colon,
454 to specify a breakpoint in another file (possibly one that hasn't been loaded
455 yet). The file is searched on :data:`sys.path`. Acceptable forms of *filename*
456 are ``/abspath/to/file.py``, ``relpath/file.py``, ``module`` and
457 ``package.module``.
458
459 With a *function* argument, set a break at the first executable statement within
460 that function. *function* can be any expression that evaluates to a function
461 in the current namespace.
462
463 If a second argument is present, it is an expression which must evaluate to
464 true before the breakpoint is honored.
465
466 Without argument, list all breaks, including for each breakpoint, the number
467 of times that breakpoint has been hit, the current ignore count, and the
468 associated condition if any.
469
470 Each breakpoint is assigned a number to which all the other
471 breakpoint commands refer.
472
473 .. pdbcommand:: tbreak [([filename:]lineno | function) [, condition]]
474
475 Temporary breakpoint, which is removed automatically when it is first hit.
476 The arguments are the same as for :pdbcmd:`break`.
477
478 .. pdbcommand:: cl(ear) [filename:lineno | bpnumber ...]
479
480 With a *filename:lineno* argument, clear all the breakpoints at this line.
481 With a space separated list of breakpoint numbers, clear those breakpoints.
482 Without argument, clear all breaks (but first ask confirmation).
483
484 .. pdbcommand:: disable bpnumber [bpnumber ...]
485
486 Disable the breakpoints given as a space separated list of breakpoint
487 numbers. Disabling a breakpoint means it cannot cause the program to stop
488 execution, but unlike clearing a breakpoint, it remains in the list of
489 breakpoints and can be (re-)enabled.
490
491 .. pdbcommand:: enable bpnumber [bpnumber ...]
492
493 Enable the breakpoints specified.
494
495 .. pdbcommand:: ignore bpnumber [count]
496
497 Set the ignore count for the given breakpoint number. If *count* is omitted,
498 the ignore count is set to 0. A breakpoint becomes active when the ignore
499 count is zero. When non-zero, the *count* is decremented each time the
500 breakpoint is reached and the breakpoint is not disabled and any associated
501 condition evaluates to true.
502
503 .. pdbcommand:: condition bpnumber [condition]
504
505 Set a new *condition* for the breakpoint, an expression which must evaluate
506 to true before the breakpoint is honored. If *condition* is absent, any
507 existing condition is removed; i.e., the breakpoint is made unconditional.
508
509 .. pdbcommand:: commands [bpnumber]
510
511 Specify a list of commands for breakpoint number *bpnumber*. The commands
512 themselves appear on the following lines. Type a line containing just
513 ``end`` to terminate the commands. An example::
514
515 (Pdb) commands 1
516 (com) p some_variable
517 (com) end
518 (Pdb)
519
520 To remove all commands from a breakpoint, type ``commands`` and follow it
521 immediately with ``end``; that is, give no commands.
522
523 With no *bpnumber* argument, ``commands`` refers to the last breakpoint set.
524
525 You can use breakpoint commands to start your program up again. Simply use
526 the :pdbcmd:`continue` command, or :pdbcmd:`step`,
527 or any other command that resumes execution.
528
529 Specifying any command resuming execution
530 (currently :pdbcmd:`continue`, :pdbcmd:`step`, :pdbcmd:`next`,
531 :pdbcmd:`return`, :pdbcmd:`until`, :pdbcmd:`jump`, :pdbcmd:`quit` and their abbreviations)
532 terminates the command list (as if
533 that command was immediately followed by end). This is because any time you
534 resume execution (even with a simple next or step), you may encounter another
535 breakpoint—which could have its own command list, leading to ambiguities about
536 which list to execute.
537
538 If the list of commands contains the ``silent`` command, or a command that
539 resumes execution, then the breakpoint message containing information about
540 the frame is not displayed.
541
542 .. versionchanged:: 3.14
543 Frame information will not be displayed if a command that resumes execution
544 is present in the command list.
545
546 .. pdbcommand:: s(tep)
547
548 Execute the current line, stop at the first possible occasion (either in a
549 function that is called or on the next line in the current function).
550
551 .. pdbcommand:: n(ext)
552
553 Continue execution until the next line in the current function is reached or
554 it returns. (The difference between :pdbcmd:`next` and :pdbcmd:`step` is
555 that :pdbcmd:`step` stops inside a called function, while :pdbcmd:`next`
556 executes called functions at (nearly) full speed, only stopping at the next
557 line in the current function.)
558
559 .. pdbcommand:: unt(il) [lineno]
560
561 Without argument, continue execution until the line with a number greater
562 than the current one is reached.
563
564 With *lineno*, continue execution until a line with a number greater or
565 equal to *lineno* is reached. In both cases, also stop when the current frame
566 returns.
567
568 .. versionchanged:: 3.2
569 Allow giving an explicit line number.
570
571 .. pdbcommand:: r(eturn)
572
573 Continue execution until the current function returns.
574
575 .. pdbcommand:: c(ont(inue))
576
577 Continue execution, only stop when a breakpoint is encountered.
578
579 .. pdbcommand:: j(ump) lineno
580
581 Set the next line that will be executed. Only available in the bottom-most
582 frame. This lets you jump back and execute code again, or jump forward to
583 skip code that you don't want to run.
584
585 It should be noted that not all jumps are allowed -- for instance it is not
586 possible to jump into the middle of a :keyword:`for` loop or out of a
587 :keyword:`finally` clause.
588
589 .. pdbcommand:: l(ist) [first[, last]]
590
591 List source code for the current file. Without arguments, list 11 lines
592 around the current line or continue the previous listing. With ``.`` as
593 argument, list 11 lines around the current line. With one argument,
594 list 11 lines around at that line. With two arguments, list the given range;
595 if the second argument is less than the first, it is interpreted as a count.
596
597 The current line in the current frame is indicated by ``->``. If an
598 exception is being debugged, the line where the exception was originally
599 raised or propagated is indicated by ``>>``, if it differs from the current
600 line.
601
602 .. versionchanged:: 3.2
603 Added the ``>>`` marker.
604
605 .. pdbcommand:: ll | longlist
606
607 List all source code for the current function or frame. Interesting lines
608 are marked as for :pdbcmd:`list`.
609
610 .. versionadded:: 3.2
611
612 .. pdbcommand:: a(rgs)
613
614 Print the arguments of the current function and their current values.
615
616 .. pdbcommand:: p expression
617
618 Evaluate *expression* in the current context and print its value.
619
620 .. note::
621
622 ``print()`` can also be used, but is not a debugger command --- this executes the
623 Python :func:`print` function.
624
625
626 .. pdbcommand:: pp expression
627
628 Like the :pdbcmd:`p` command, except the value of *expression* is
629 pretty-printed using the :mod:`pprint` module.
630
631 .. pdbcommand:: whatis expression
632
633 Print the type of *expression*.
634
635 .. pdbcommand:: source expression
636
637 Try to get source code of *expression* and display it.
638
639 .. versionadded:: 3.2
640
641 .. pdbcommand:: display [expression]
642
643 Display the value of *expression* if it changed, each time execution stops
644 in the current frame.
645
646 Without *expression*, list all display expressions for the current frame.
647
648 .. note::
649
650 Display evaluates *expression* and compares to the result of the previous
651 evaluation of *expression*, so when the result is mutable, display may not
652 be able to pick up the changes.
653
654 Example::
655
656 lst = []
657 breakpoint()
658 pass
659 lst.append(1)
660 print(lst)
661
662 Display won't realize ``lst`` has been changed because the result of evaluation
663 is modified in place by ``lst.append(1)`` before being compared::
664
665 > example.py(3)<module>()
666 -> pass
667 (Pdb) display lst
668 display lst: []
669 (Pdb) n
670 > example.py(4)<module>()
671 -> lst.append(1)
672 (Pdb) n
673 > example.py(5)<module>()
674 -> print(lst)
675 (Pdb)
676
677 You can do some tricks with copy mechanism to make it work::
678
679 > example.py(3)<module>()
680 -> pass
681 (Pdb) display lst[:]
682 display lst[:]: []
683 (Pdb) n
684 > example.py(4)<module>()
685 -> lst.append(1)
686 (Pdb) n
687 > example.py(5)<module>()
688 -> print(lst)
689 display lst[:]: [1] [old: []]
690 (Pdb)
691
692 .. versionadded:: 3.2
693
694 .. pdbcommand:: undisplay [expression]
695
696 Do not display *expression* anymore in the current frame. Without
697 *expression*, clear all display expressions for the current frame.
698
699 .. versionadded:: 3.2
700
701 .. pdbcommand:: interact
702
703 Start an interactive interpreter (using the :mod:`code` module) in a new
704 global namespace initialised from the local and global namespaces for the
705 current scope. Use ``exit()`` or ``quit()`` to exit the interpreter and
706 return to the debugger.
707
708 .. note::
709
710 As ``interact`` creates a new dedicated namespace for code execution,
711 assignments to variables will not affect the original namespaces.
712 However, modifications to any referenced mutable objects will be reflected
713 in the original namespaces as usual.
714
715 .. versionadded:: 3.2
716
717 .. versionchanged:: 3.13
718 ``exit()`` and ``quit()`` can be used to exit the :pdbcmd:`interact`
719 command.
720
721 .. versionchanged:: 3.13
722 :pdbcmd:`interact` directs its output to the debugger's
723 output channel rather than :data:`sys.stderr`.
724
725 .. _debugger-aliases:
726
727 .. pdbcommand:: alias [name [command]]
728
729 Create an alias called *name* that executes *command*. The *command* must
730 *not* be enclosed in quotes. Replaceable parameters can be indicated by
731 ``%1``, ``%2``, ... and ``%9``, while ``%*`` is replaced by all the parameters.
732 If *command* is omitted, the current alias for *name* is shown. If no
733 arguments are given, all aliases are listed.
734
735 Aliases may be nested and can contain anything that can be legally typed at
736 the pdb prompt. Note that internal pdb commands *can* be overridden by
737 aliases. Such a command is then hidden until the alias is removed. Aliasing
738 is recursively applied to the first word of the command line; all other words
739 in the line are left alone.
740
741 As an example, here are two useful aliases (especially when placed in the
742 :file:`.pdbrc` file)::
743
744 # Print instance variables (usage "pi classInst")
745 alias pi for k in %1.__dict__.keys(): print(f"%1.{k} = {%1.__dict__[k]}")
746 # Print instance variables in self
747 alias ps pi self
748
749 .. pdbcommand:: unalias name
750
751 Delete the specified alias *name*.
752
753 .. pdbcommand:: ! statement
754
755 Execute the (one-line) *statement* in the context of the current stack frame.
756 The exclamation point can be omitted unless the first word of the statement
757 resembles a debugger command, e.g.:
758
759 .. code-block:: none
760
761 (Pdb) ! n=42
762 (Pdb)
763
764 To set a global variable, you can prefix the assignment command with a
765 :keyword:`global` statement on the same line, e.g.:
766
767 .. code-block:: none
768
769 (Pdb) global list_options; list_options = ['-l']
770 (Pdb)
771
772 .. pdbcommand:: run [args ...]
773 restart [args ...]
774
775 Restart the debugged Python program. If *args* is supplied, it is split
776 with :mod:`shlex` and the result is used as the new :data:`sys.argv`.
777 History, breakpoints, actions and debugger options are preserved.
778 :pdbcmd:`restart` is an alias for :pdbcmd:`run`.
779
780 .. versionchanged:: 3.14
781 :pdbcmd:`run` and :pdbcmd:`restart` commands are disabled when the
782 debugger is invoked in ``'inline'`` mode.
783
784 .. pdbcommand:: q(uit)
785
786 Quit from the debugger. The program being executed is aborted.
787 An end-of-file input is equivalent to :pdbcmd:`quit`.
788
789 A confirmation prompt will be shown if the debugger is invoked in
790 ``'inline'`` mode. Either ``y``, ``Y``, ``<Enter>`` or ``EOF``
791 will confirm the quit.
792
793 .. versionchanged:: 3.14
794 A confirmation prompt will be shown if the debugger is invoked in
795 ``'inline'`` mode. After the confirmation, the debugger will call
796 :func:`sys.exit` immediately, instead of raising :exc:`bdb.BdbQuit`
797 in the next trace event.
798
799 .. pdbcommand:: debug code
800
801 Enter a recursive debugger that steps through *code*
802 (which is an arbitrary expression or statement to be
803 executed in the current environment).
804
805 .. pdbcommand:: retval
806
807 Print the return value for the last return of the current function.
808
809 .. pdbcommand:: exceptions [excnumber]
810
811 List or jump between chained exceptions.
812
813 When using ``pdb.pm()`` or ``Pdb.post_mortem(...)`` with a chained exception
814 instead of a traceback, it allows the user to move between the
815 chained exceptions using ``exceptions`` command to list exceptions, and
816 ``exceptions <number>`` to switch to that exception.
817
818
819 Example::
820
821 def out():
822 try:
823 middle()
824 except Exception as e:
825 raise ValueError("reraise middle() error") from e
826
827 def middle():
828 try:
829 return inner(0)
830 except Exception as e:
831 raise ValueError("Middle fail")
832
833 def inner(x):
834 1 / x
835
836 out()
837
838 calling ``pdb.pm()`` will allow to move between exceptions::
839
840 > example.py(5)out()
841 -> raise ValueError("reraise middle() error") from e
842
843 (Pdb) exceptions
844 0 ZeroDivisionError('division by zero')
845 1 ValueError('Middle fail')
846 > 2 ValueError('reraise middle() error')
847
848 (Pdb) exceptions 0
849 > example.py(16)inner()
850 -> 1 / x
851
852 (Pdb) up
853 > example.py(10)middle()
854 -> return inner(0)
855
856 .. versionadded:: 3.13
857
858 .. rubric:: Footnotes
859
860 .. [1] Whether a frame is considered to originate in a certain module
861 is determined by the ``__name__`` in the frame globals.