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
15The module :mod:`pdb` defines an interactive source code debugger for Python
16programs.  It supports setting (conditional) breakpoints and single stepping at
17the source line level, inspection of stack frames, source code listing, and
18evaluation of arbitrary Python code in the context of any stack frame.  It also
19supports 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
26The debugger is extensible -- it is actually defined as the class :class:`Pdb`.
27This is currently undocumented but easily understood by reading the source.  The
28extension 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
39The typical usage to break into the debugger is to insert::
40
41   import pdb; pdb.set_trace()
42
43Or::
44
45   breakpoint()
46
47at the location you want to break into the debugger, and then run the program.
48You can then step through the code following this statement, and continue
49running without the debugger using the :pdbcmd:`continue` command.
50
51.. versionadded:: 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
63The debugger's prompt is ``(Pdb)``, which is the indicator that you are in debug mode::
64
65   > ...(3)double()
66   -> return x * 2
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
78You can also invoke :mod:`pdb` from the command line to debug other scripts.  For
79example::
80
81   python -m pdb myscript.py
82
83When invoked as a module, pdb will automatically enter post-mortem debugging if
84the program being debugged exits abnormally.  After post-mortem debugging (or
85after normal exit of the program), pdb will restart the program.  Automatic
86restarting preserves pdb's state (such as breakpoints) and in most cases is more
87useful than quitting the debugger upon program's exit.
88
89.. versionadded:: 3.2
90   ``-c`` option is introduced to execute commands as if given
91   in a :file:`.pdbrc` file, see :ref:`debugger-commands`.
92
93.. versionadded:: 3.7
94   ``-m`` option is introduced to execute modules similar to the way
95   ``python -m`` does. As with a script, the debugger will pause execution just
96   before the first line of the module.
97
98Typical usage to execute a statement under control of the debugger is::
99
100   >>> import pdb
101   >>> def f(x):
102   ...     print(1 / x)
103   >>> pdb.run("f(2)")
104   > <string>(1)<module>()
105   (Pdb) continue
106   0.5
107   >>>
108
109The typical usage to inspect a crashed program is::
110
111   >>> import pdb
112   >>> def f(x):
113   ...     print(1 / x)
114   ...
115   >>> f(0)
116   Traceback (most recent call last):
117     File "<stdin>", line 1, in <module>
118     File "<stdin>", line 2, in f
119   ZeroDivisionError: division by zero
120   >>> pdb.pm()
121   > <stdin>(2)f()
122   (Pdb) p x
123   0
124   (Pdb)
125
126
127The module defines the following functions; each enters the debugger in a
128slightly different way:
129
130.. function:: run(statement, globals=None, locals=None)
131
132   Execute the *statement* (given as a string or a code object) under debugger
133   control.  The debugger prompt appears before any code is executed; you can
134   set breakpoints and type :pdbcmd:`continue`, or you can step through the
135   statement using :pdbcmd:`step` or :pdbcmd:`next` (all these commands are
136   explained below).  The optional *globals* and *locals* arguments specify the
137   environment in which the code is executed; by default the dictionary of the
138   module :mod:`__main__` is used.  (See the explanation of the built-in
139   :func:`exec` or :func:`eval` functions.)
140
141
142.. function:: runeval(expression, globals=None, locals=None)
143
144   Evaluate the *expression* (given as a string or a code object) under debugger
145   control.  When :func:`runeval` returns, it returns the value of the
146   *expression*.  Otherwise this function is similar to :func:`run`.
147
148
149.. function:: runcall(function, *args, **kwds)
150
151   Call the *function* (a function or method object, not a string) with the
152   given arguments.  When :func:`runcall` returns, it returns whatever the
153   function call returned.  The debugger prompt appears as soon as the function
154   is entered.
155
156
157.. function:: set_trace(*, header=None)
158
159   Enter the debugger at the calling stack frame.  This is useful to hard-code
160   a breakpoint at a given point in a program, even if the code is not
161   otherwise being debugged (e.g. when an assertion fails).  If given,
162   *header* is printed to the console just before debugging begins.
163
164   .. versionchanged:: 3.7
165      The keyword-only argument *header*.
166
167
168.. function:: post_mortem(traceback=None)
169
170   Enter post-mortem debugging of the given *traceback* object.  If no
171   *traceback* is given, it uses the one of the exception that is currently
172   being handled (an exception must be being handled if the default is to be
173   used).
174
175
176.. function:: pm()
177
178   Enter post-mortem debugging of the traceback found in
179   :data:`sys.last_traceback`.
180
181
182The ``run*`` functions and :func:`set_trace` are aliases for instantiating the
183:class:`Pdb` class and calling the method of the same name.  If you want to
184access further features, you have to do this yourself:
185
186.. class:: Pdb(completekey='tab', stdin=None, stdout=None, skip=None, \
187               nosigint=False, readrc=True)
188
189   :class:`Pdb` is the debugger class.
190
191   The *completekey*, *stdin* and *stdout* arguments are passed to the
192   underlying :class:`cmd.Cmd` class; see the description there.
193
194   The *skip* argument, if given, must be an iterable of glob-style module name
195   patterns.  The debugger will not step into frames that originate in a module
196   that matches one of these patterns. [1]_
197
198   By default, Pdb sets a handler for the SIGINT signal (which is sent when the
199   user presses :kbd:`Ctrl-C` on the console) when you give a :pdbcmd:`continue` command.
200   This allows you to break into the debugger again by pressing :kbd:`Ctrl-C`.  If you
201   want Pdb not to touch the SIGINT handler, set *nosigint* to true.
202
203   The *readrc* argument defaults to true and controls whether Pdb will load
204   .pdbrc files from the filesystem.
205
206   Example call to enable tracing with *skip*::
207
208      import pdb; pdb.Pdb(skip=['django.*']).set_trace()
209
210   .. audit-event:: pdb.Pdb "" pdb.Pdb
211
212   .. versionadded:: 3.1
213      The *skip* argument.
214
215   .. versionadded:: 3.2
216      The *nosigint* argument.  Previously, a SIGINT handler was never set by
217      Pdb.
218
219   .. versionchanged:: 3.6
220      The *readrc* argument.
221
222   .. method:: run(statement, globals=None, locals=None)
223               runeval(expression, globals=None, locals=None)
224               runcall(function, *args, **kwds)
225               set_trace()
226
227      See the documentation for the functions explained above.
228
229
230.. _debugger-commands:
231
232Debugger Commands
233-----------------
234
235The commands recognized by the debugger are listed below.  Most commands can be
236abbreviated to one or two letters as indicated; e.g. ``h(elp)`` means that
237either ``h`` or ``help`` can be used to enter the help command (but not ``he``
238or ``hel``, nor ``H`` or ``Help`` or ``HELP``).  Arguments to commands must be
239separated by whitespace (spaces or tabs).  Optional arguments are enclosed in
240square brackets (``[]``) in the command syntax; the square brackets must not be
241typed.  Alternatives in the command syntax are separated by a vertical bar
242(``|``).
243
244Entering a blank line repeats the last command entered.  Exception: if the last
245command was a :pdbcmd:`list` command, the next 11 lines are listed.
246
247Commands that the debugger doesn't recognize are assumed to be Python statements
248and are executed in the context of the program being debugged.  Python
249statements can also be prefixed with an exclamation point (``!``).  This is a
250powerful way to inspect the program being debugged; it is even possible to
251change a variable or call a function.  When an exception occurs in such a
252statement, the exception name is printed but the debugger's state is not
253changed.
254
255The debugger supports :ref:`aliases <debugger-aliases>`.  Aliases can have
256parameters which allows one a certain level of adaptability to the context under
257examination.
258
259Multiple commands may be entered on a single line, separated by ``;;``.  (A
260single ``;`` is not used as it is the separator for multiple commands in a line
261that is passed to the Python parser.)  No intelligence is applied to separating
262the commands; the input is split at the first ``;;`` pair, even if it is in the
263middle of a quoted string. A workaround for strings with double semicolons
264is to use implicit string concatenation ``';'';'`` or ``";"";"``.
265
266.. index::
267   pair: .pdbrc; file
268   triple: debugger; configuration; file
269
270If a file :file:`.pdbrc` exists in the user's home directory or in the current
271directory, it is read with ``'utf-8'`` encoding and executed as if it had been
272typed at the debugger prompt.  This is particularly useful for aliases.  If both
273files exist, the one in the home directory is read first and aliases defined there
274can be overridden by the local file.
275
276.. versionchanged:: 3.11
277   :file:`.pdbrc` is now read with ``'utf-8'`` encoding. Previously, it was read
278   with the system locale encoding.
279
280.. versionchanged:: 3.2
281   :file:`.pdbrc` can now contain commands that continue debugging, such as
282   :pdbcmd:`continue` or :pdbcmd:`next`.  Previously, these commands had no
283   effect.
284
285
286.. pdbcommand:: h(elp) [command]
287
288   Without argument, print the list of available commands.  With a *command* as
289   argument, print help about that command.  ``help pdb`` displays the full
290   documentation (the docstring of the :mod:`pdb` module).  Since the *command*
291   argument must be an identifier, ``help exec`` must be entered to get help on
292   the ``!`` command.
293
294.. pdbcommand:: w(here)
295
296   Print a stack trace, with the most recent frame at the bottom.  An arrow (``>``)
297   indicates the current frame, which determines the context of most commands.
298
299.. pdbcommand:: d(own) [count]
300
301   Move the current frame *count* (default one) levels down in the stack trace
302   (to a newer frame).
303
304.. pdbcommand:: u(p) [count]
305
306   Move the current frame *count* (default one) levels up in the stack trace (to
307   an older frame).
308
309.. pdbcommand:: b(reak) [([filename:]lineno | function) [, condition]]
310
311   With a *lineno* argument, set a break there in the current file.  With a
312   *function* argument, set a break at the first executable statement within
313   that function.  The line number may be prefixed with a filename and a colon,
314   to specify a breakpoint in another file (probably one that hasn't been loaded
315   yet).  The file is searched on :data:`sys.path`.  Note that each breakpoint
316   is assigned a number to which all the other breakpoint commands refer.
317
318   If a second argument is present, it is an expression which must evaluate to
319   true before the breakpoint is honored.
320
321   Without argument, list all breaks, including for each breakpoint, the number
322   of times that breakpoint has been hit, the current ignore count, and the
323   associated condition if any.
324
325.. pdbcommand:: tbreak [([filename:]lineno | function) [, condition]]
326
327   Temporary breakpoint, which is removed automatically when it is first hit.
328   The arguments are the same as for :pdbcmd:`break`.
329
330.. pdbcommand:: cl(ear) [filename:lineno | bpnumber ...]
331
332   With a *filename:lineno* argument, clear all the breakpoints at this line.
333   With a space separated list of breakpoint numbers, clear those breakpoints.
334   Without argument, clear all breaks (but first ask confirmation).
335
336.. pdbcommand:: disable [bpnumber ...]
337
338   Disable the breakpoints given as a space separated list of breakpoint
339   numbers.  Disabling a breakpoint means it cannot cause the program to stop
340   execution, but unlike clearing a breakpoint, it remains in the list of
341   breakpoints and can be (re-)enabled.
342
343.. pdbcommand:: enable [bpnumber ...]
344
345   Enable the breakpoints specified.
346
347.. pdbcommand:: ignore bpnumber [count]
348
349   Set the ignore count for the given breakpoint number.  If *count* is omitted,
350   the ignore count is set to 0.  A breakpoint becomes active when the ignore
351   count is zero.  When non-zero, the *count* is decremented each time the
352   breakpoint is reached and the breakpoint is not disabled and any associated
353   condition evaluates to true.
354
355.. pdbcommand:: condition bpnumber [condition]
356
357   Set a new *condition* for the breakpoint, an expression which must evaluate
358   to true before the breakpoint is honored.  If *condition* is absent, any
359   existing condition is removed; i.e., the breakpoint is made unconditional.
360
361.. pdbcommand:: commands [bpnumber]
362
363   Specify a list of commands for breakpoint number *bpnumber*.  The commands
364   themselves appear on the following lines.  Type a line containing just
365   ``end`` to terminate the commands. An example::
366
367      (Pdb) commands 1
368      (com) p some_variable
369      (com) end
370      (Pdb)
371
372   To remove all commands from a breakpoint, type ``commands`` and follow it
373   immediately with ``end``; that is, give no commands.
374
375   With no *bpnumber* argument, ``commands`` refers to the last breakpoint set.
376
377   You can use breakpoint commands to start your program up again.  Simply use
378   the :pdbcmd:`continue` command, or :pdbcmd:`step`,
379   or any other command that resumes execution.
380
381   Specifying any command resuming execution
382   (currently :pdbcmd:`continue`, :pdbcmd:`step`, :pdbcmd:`next`,
383   :pdbcmd:`return`, :pdbcmd:`jump`, :pdbcmd:`quit` and their abbreviations)
384   terminates the command list (as if
385   that command was immediately followed by end). This is because any time you
386   resume execution (even with a simple next or step), you may encounter another
387   breakpoint—which could have its own command list, leading to ambiguities about
388   which list to execute.
389
390   If you use the ``silent`` command in the command list, the usual message about
391   stopping at a breakpoint is not printed.  This may be desirable for breakpoints
392   that are to print a specific message and then continue.  If none of the other
393   commands print anything, you see no sign that the breakpoint was reached.
394
395.. pdbcommand:: s(tep)
396
397   Execute the current line, stop at the first possible occasion (either in a
398   function that is called or on the next line in the current function).
399
400.. pdbcommand:: n(ext)
401
402   Continue execution until the next line in the current function is reached or
403   it returns.  (The difference between :pdbcmd:`next` and :pdbcmd:`step` is
404   that :pdbcmd:`step` stops inside a called function, while :pdbcmd:`next`
405   executes called functions at (nearly) full speed, only stopping at the next
406   line in the current function.)
407
408.. pdbcommand:: unt(il) [lineno]
409
410   Without argument, continue execution until the line with a number greater
411   than the current one is reached.
412
413   With *lineno*, continue execution until a line with a number greater or
414   equal to *lineno* is reached.  In both cases, also stop when the current frame
415   returns.
416
417   .. versionchanged:: 3.2
418      Allow giving an explicit line number.
419
420.. pdbcommand:: r(eturn)
421
422   Continue execution until the current function returns.
423
424.. pdbcommand:: c(ont(inue))
425
426   Continue execution, only stop when a breakpoint is encountered.
427
428.. pdbcommand:: j(ump) lineno
429
430   Set the next line that will be executed.  Only available in the bottom-most
431   frame.  This lets you jump back and execute code again, or jump forward to
432   skip code that you don't want to run.
433
434   It should be noted that not all jumps are allowed -- for instance it is not
435   possible to jump into the middle of a :keyword:`for` loop or out of a
436   :keyword:`finally` clause.
437
438.. pdbcommand:: l(ist) [first[, last]]
439
440   List source code for the current file.  Without arguments, list 11 lines
441   around the current line or continue the previous listing.  With ``.`` as
442   argument, list 11 lines around the current line.  With one argument,
443   list 11 lines around at that line.  With two arguments, list the given range;
444   if the second argument is less than the first, it is interpreted as a count.
445
446   The current line in the current frame is indicated by ``->``.  If an
447   exception is being debugged, the line where the exception was originally
448   raised or propagated is indicated by ``>>``, if it differs from the current
449   line.
450
451   .. versionadded:: 3.2
452      The ``>>`` marker.
453
454.. pdbcommand:: ll | longlist
455
456   List all source code for the current function or frame.  Interesting lines
457   are marked as for :pdbcmd:`list`.
458
459   .. versionadded:: 3.2
460
461.. pdbcommand:: a(rgs)
462
463   Print the arguments of the current function and their current values.
464
465.. pdbcommand:: p expression
466
467   Evaluate *expression* in the current context and print its value.
468
469   .. note::
470
471      ``print()`` can also be used, but is not a debugger command --- this executes the
472      Python :func:`print` function.
473
474
475.. pdbcommand:: pp expression
476
477   Like the :pdbcmd:`p` command, except the value of *expression* is
478   pretty-printed using the :mod:`pprint` module.
479
480.. pdbcommand:: whatis expression
481
482   Print the type of *expression*.
483
484.. pdbcommand:: source expression
485
486   Try to get source code of *expression* and display it.
487
488   .. versionadded:: 3.2
489
490.. pdbcommand:: display [expression]
491
492   Display the value of *expression* if it changed, each time execution stops
493   in the current frame.
494
495   Without *expression*, list all display expressions for the current frame.
496
497   .. note::
498
499      Display evaluates *expression* and compares to the result of the previous
500      evaluation of *expression*, so when the result is mutable, display may not
501      be able to pick up the changes.
502
503   Example::
504
505      lst = []
506      breakpoint()
507      pass
508      lst.append(1)
509      print(lst)
510
511   Display won't realize ``lst`` has been changed because the result of evaluation
512   is modified in place by ``lst.append(1)`` before being compared::
513
514      > example.py(3)<module>()
515      -> pass
516      (Pdb) display lst
517      display lst: []
518      (Pdb) n
519      > example.py(4)<module>()
520      -> lst.append(1)
521      (Pdb) n
522      > example.py(5)<module>()
523      -> print(lst)
524      (Pdb)
525
526   You can do some tricks with copy mechanism to make it work::
527
528      > example.py(3)<module>()
529      -> pass
530      (Pdb) display lst[:]
531      display lst[:]: []
532      (Pdb) n
533      > example.py(4)<module>()
534      -> lst.append(1)
535      (Pdb) n
536      > example.py(5)<module>()
537      -> print(lst)
538      display lst[:]: [1]  [old: []]
539      (Pdb)
540
541   .. versionadded:: 3.2
542
543.. pdbcommand:: undisplay [expression]
544
545   Do not display *expression* anymore in the current frame.  Without
546   *expression*, clear all display expressions for the current frame.
547
548   .. versionadded:: 3.2
549
550.. pdbcommand:: interact
551
552   Start an interactive interpreter (using the :mod:`code` module) whose global
553   namespace contains all the (global and local) names found in the current
554   scope.
555
556   .. versionadded:: 3.2
557
558.. _debugger-aliases:
559
560.. pdbcommand:: alias [name [command]]
561
562   Create an alias called *name* that executes *command*.  The *command* must
563   *not* be enclosed in quotes.  Replaceable parameters can be indicated by
564   ``%1``, ``%2``, and so on, while ``%*`` is replaced by all the parameters.
565   If *command* is omitted, the current alias for *name* is shown. If no
566   arguments are given, all aliases are listed.
567
568   Aliases may be nested and can contain anything that can be legally typed at
569   the pdb prompt.  Note that internal pdb commands *can* be overridden by
570   aliases.  Such a command is then hidden until the alias is removed.  Aliasing
571   is recursively applied to the first word of the command line; all other words
572   in the line are left alone.
573
574   As an example, here are two useful aliases (especially when placed in the
575   :file:`.pdbrc` file)::
576
577      # Print instance variables (usage "pi classInst")
578      alias pi for k in %1.__dict__.keys(): print(f"%1.{k} = {%1.__dict__[k]}")
579      # Print instance variables in self
580      alias ps pi self
581
582.. pdbcommand:: unalias name
583
584   Delete the specified alias *name*.
585
586.. pdbcommand:: ! statement
587
588   Execute the (one-line) *statement* in the context of the current stack frame.
589   The exclamation point can be omitted unless the first word of the statement
590   resembles a debugger command.  To set a global variable, you can prefix the
591   assignment command with a :keyword:`global` statement on the same line,
592   e.g.::
593
594      (Pdb) global list_options; list_options = ['-l']
595      (Pdb)
596
597.. pdbcommand:: run [args ...]
598                restart [args ...]
599
600   Restart the debugged Python program.  If *args* is supplied, it is split
601   with :mod:`shlex` and the result is used as the new :data:`sys.argv`.
602   History, breakpoints, actions and debugger options are preserved.
603   :pdbcmd:`restart` is an alias for :pdbcmd:`run`.
604
605.. pdbcommand:: q(uit)
606
607   Quit from the debugger.  The program being executed is aborted.
608
609.. pdbcommand:: debug code
610
611   Enter a recursive debugger that steps through *code*
612   (which is an arbitrary expression or statement to be
613   executed in the current environment).
614
615.. pdbcommand:: retval
616
617   Print the return value for the last return of the current function.
618
619.. rubric:: Footnotes
620
621.. [1] Whether a frame is considered to originate in a certain module
622       is determined by the ``__name__`` in the frame globals.
623