blob: 9a333494cd37685d9f32fd4e314b9b7935e65bd1 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _debugger:
2
Georg Brandl546e2d62007-09-12 18:04:37 +00003:mod:`pdb` --- The Python Debugger
4==================================
Georg Brandl116aa622007-08-15 14:28:22 +00005
6.. module:: pdb
7 :synopsis: The Python debugger for interactive interpreters.
8
9
10.. index:: single: debugging
11
12The module :mod:`pdb` defines an interactive source code debugger for Python
13programs. It supports setting (conditional) breakpoints and single stepping at
14the source line level, inspection of stack frames, source code listing, and
15evaluation of arbitrary Python code in the context of any stack frame. It also
16supports post-mortem debugging and can be called under program control.
17
18.. index::
19 single: Pdb (class in pdb)
20 module: bdb
21 module: cmd
22
23The debugger is extensible --- it is actually defined as the class :class:`Pdb`.
24This is currently undocumented but easily understood by reading the source. The
Georg Brandl1f70cdf2010-03-21 09:04:24 +000025extension interface uses the modules :mod:`bdb` and :mod:`cmd`.
Georg Brandl116aa622007-08-15 14:28:22 +000026
27The debugger's prompt is ``(Pdb)``. Typical usage to run a program under control
28of the debugger is::
29
30 >>> import pdb
31 >>> import mymodule
32 >>> pdb.run('mymodule.test()')
33 > <string>(0)?()
34 (Pdb) continue
35 > <string>(1)?()
36 (Pdb) continue
37 NameError: 'spam'
38 > <string>(1)?()
Georg Brandl48310cd2009-01-03 21:18:54 +000039 (Pdb)
Georg Brandl116aa622007-08-15 14:28:22 +000040
41:file:`pdb.py` can also be invoked as a script to debug other scripts. For
42example::
43
Georg Brandl45bb63f2009-09-16 09:42:19 +000044 python3 -m pdb myscript.py
Georg Brandl116aa622007-08-15 14:28:22 +000045
46When invoked as a script, pdb will automatically enter post-mortem debugging if
47the program being debugged exits abnormally. After post-mortem debugging (or
48after normal exit of the program), pdb will restart the program. Automatic
49restarting preserves pdb's state (such as breakpoints) and in most cases is more
50useful than quitting the debugger upon program's exit.
51
Georg Brandl243ad662009-05-05 09:00:19 +000052The typical usage to break into the debugger from a running program is to
53insert ::
54
55 import pdb; pdb.set_trace()
56
57at the location you want to break into the debugger. You can then step through
Benjamin Petersona0dfa822009-11-13 02:25:08 +000058the code following this statement, and continue running without the debugger using
Georg Brandl243ad662009-05-05 09:00:19 +000059the ``c`` command.
60
61The typical usage to inspect a crashed program is::
Georg Brandl116aa622007-08-15 14:28:22 +000062
63 >>> import pdb
64 >>> import mymodule
65 >>> mymodule.test()
66 Traceback (most recent call last):
67 File "<stdin>", line 1, in ?
68 File "./mymodule.py", line 4, in test
69 test2()
70 File "./mymodule.py", line 3, in test2
Georg Brandlc9879242007-09-04 07:07:56 +000071 print(spam)
Georg Brandl116aa622007-08-15 14:28:22 +000072 NameError: spam
73 >>> pdb.pm()
74 > ./mymodule.py(3)test2()
Georg Brandlc9879242007-09-04 07:07:56 +000075 -> print(spam)
Georg Brandl48310cd2009-01-03 21:18:54 +000076 (Pdb)
Georg Brandl116aa622007-08-15 14:28:22 +000077
Georg Brandl243ad662009-05-05 09:00:19 +000078
Georg Brandl116aa622007-08-15 14:28:22 +000079The module defines the following functions; each enters the debugger in a
80slightly different way:
81
Georg Brandl18244152009-09-02 20:34:52 +000082.. function:: run(statement, globals=None, locals=None)
Georg Brandl116aa622007-08-15 14:28:22 +000083
84 Execute the *statement* (given as a string) under debugger control. The
85 debugger prompt appears before any code is executed; you can set breakpoints and
86 type ``continue``, or you can step through the statement using ``step`` or
87 ``next`` (all these commands are explained below). The optional *globals* and
88 *locals* arguments specify the environment in which the code is executed; by
89 default the dictionary of the module :mod:`__main__` is used. (See the
90 explanation of the built-in :func:`exec` or :func:`eval` functions.)
91
92
Georg Brandl18244152009-09-02 20:34:52 +000093.. function:: runeval(expression, globals=None, locals=None)
Georg Brandl116aa622007-08-15 14:28:22 +000094
95 Evaluate the *expression* (given as a string) under debugger control. When
96 :func:`runeval` returns, it returns the value of the expression. Otherwise this
97 function is similar to :func:`run`.
98
99
Georg Brandl18244152009-09-02 20:34:52 +0000100.. function:: runcall(function, *args, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102 Call the *function* (a function or method object, not a string) with the given
103 arguments. When :func:`runcall` returns, it returns whatever the function call
104 returned. The debugger prompt appears as soon as the function is entered.
105
106
107.. function:: set_trace()
108
109 Enter the debugger at the calling stack frame. This is useful to hard-code a
110 breakpoint at a given point in a program, even if the code is not otherwise
111 being debugged (e.g. when an assertion fails).
112
113
Georg Brandl18244152009-09-02 20:34:52 +0000114.. function:: post_mortem(traceback=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000115
Georg Brandl48310cd2009-01-03 21:18:54 +0000116 Enter post-mortem debugging of the given *traceback* object. If no
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000117 *traceback* is given, it uses the one of the exception that is currently
118 being handled (an exception must be being handled if the default is to be
119 used).
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121
122.. function:: pm()
123
Georg Brandl243ad662009-05-05 09:00:19 +0000124 Enter post-mortem debugging of the traceback found in
125 :data:`sys.last_traceback`.
126
127
128The ``run_*`` functions and :func:`set_trace` are aliases for instantiating the
129:class:`Pdb` class and calling the method of the same name. If you want to
130access further features, you have to do this yourself:
131
132.. class:: Pdb(completekey='tab', stdin=None, stdout=None, skip=None)
133
134 :class:`Pdb` is the debugger class.
135
136 The *completekey*, *stdin* and *stdout* arguments are passed to the
137 underlying :class:`cmd.Cmd` class; see the description there.
138
139 The *skip* argument, if given, must be an iterable of glob-style module name
140 patterns. The debugger will not step into frames that originate in a module
141 that matches one of these patterns. [1]_
142
143 Example call to enable tracing with *skip*::
144
145 import pdb; pdb.Pdb(skip=['django.*']).set_trace()
146
Georg Brandl705d9d52009-05-05 09:29:50 +0000147 .. versionadded:: 3.1
Georg Brandl243ad662009-05-05 09:00:19 +0000148 The *skip* argument.
149
Georg Brandl18244152009-09-02 20:34:52 +0000150 .. method:: run(statement, globals=None, locals=None)
151 runeval(expression, globals=None, locals=None)
152 runcall(function, *args, **kwds)
Georg Brandl243ad662009-05-05 09:00:19 +0000153 set_trace()
154
155 See the documentation for the functions explained above.
Georg Brandl116aa622007-08-15 14:28:22 +0000156
157
158.. _debugger-commands:
159
160Debugger Commands
161=================
162
163The debugger recognizes the following commands. Most commands can be
164abbreviated to one or two letters; e.g. ``h(elp)`` means that either ``h`` or
165``help`` can be used to enter the help command (but not ``he`` or ``hel``, nor
166``H`` or ``Help`` or ``HELP``). Arguments to commands must be separated by
167whitespace (spaces or tabs). Optional arguments are enclosed in square brackets
168(``[]``) in the command syntax; the square brackets must not be typed.
169Alternatives in the command syntax are separated by a vertical bar (``|``).
170
171Entering a blank line repeats the last command entered. Exception: if the last
172command was a ``list`` command, the next 11 lines are listed.
173
174Commands that the debugger doesn't recognize are assumed to be Python statements
175and are executed in the context of the program being debugged. Python
176statements can also be prefixed with an exclamation point (``!``). This is a
177powerful way to inspect the program being debugged; it is even possible to
178change a variable or call a function. When an exception occurs in such a
179statement, the exception name is printed but the debugger's state is not
180changed.
181
182Multiple commands may be entered on a single line, separated by ``;;``. (A
183single ``;`` is not used as it is the separator for multiple commands in a line
184that is passed to the Python parser.) No intelligence is applied to separating
185the commands; the input is split at the first ``;;`` pair, even if it is in the
186middle of a quoted string.
187
188The debugger supports aliases. Aliases can have parameters which allows one a
189certain level of adaptability to the context under examination.
190
191.. index::
192 pair: .pdbrc; file
193 triple: debugger; configuration; file
194
195If a file :file:`.pdbrc` exists in the user's home directory or in the current
196directory, it is read in and executed as if it had been typed at the debugger
197prompt. This is particularly useful for aliases. If both files exist, the one
198in the home directory is read first and aliases defined there can be overridden
199by the local file.
200
201h(elp) [*command*]
202 Without argument, print the list of available commands. With a *command* as
203 argument, print help about that command. ``help pdb`` displays the full
204 documentation file; if the environment variable :envvar:`PAGER` is defined, the
205 file is piped through that command instead. Since the *command* argument must
206 be an identifier, ``help exec`` must be entered to get help on the ``!``
207 command.
208
209w(here)
210 Print a stack trace, with the most recent frame at the bottom. An arrow
211 indicates the current frame, which determines the context of most commands.
212
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000213d(own) [*count*]
214 Move the current frame *count* (default one) levels down in the stack trace
215 (to a newer frame).
Georg Brandl116aa622007-08-15 14:28:22 +0000216
Georg Brandleb1f4aa2010-06-27 10:37:48 +0000217u(p) [*count*]
218 Move the current frame *count* (default one) levels up in the stack trace
219 (to an older frame).
Georg Brandl116aa622007-08-15 14:28:22 +0000220
Guido van Rossum61e21b52007-08-20 19:06:03 +0000221b(reak) [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
Georg Brandl116aa622007-08-15 14:28:22 +0000222 With a *lineno* argument, set a break there in the current file. With a
223 *function* argument, set a break at the first executable statement within that
224 function. The line number may be prefixed with a filename and a colon, to
225 specify a breakpoint in another file (probably one that hasn't been loaded yet).
226 The file is searched on ``sys.path``. Note that each breakpoint is assigned a
227 number to which all the other breakpoint commands refer.
228
229 If a second argument is present, it is an expression which must evaluate to true
230 before the breakpoint is honored.
231
232 Without argument, list all breaks, including for each breakpoint, the number of
233 times that breakpoint has been hit, the current ignore count, and the associated
234 condition if any.
235
Guido van Rossum61e21b52007-08-20 19:06:03 +0000236tbreak [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
Georg Brandl116aa622007-08-15 14:28:22 +0000237 Temporary breakpoint, which is removed automatically when it is first hit. The
238 arguments are the same as break.
239
240cl(ear) [*bpnumber* [*bpnumber ...*]]
241 With a space separated list of breakpoint numbers, clear those breakpoints.
242 Without argument, clear all breaks (but first ask confirmation).
243
244disable [*bpnumber* [*bpnumber ...*]]
245 Disables the breakpoints given as a space separated list of breakpoint numbers.
246 Disabling a breakpoint means it cannot cause the program to stop execution, but
247 unlike clearing a breakpoint, it remains in the list of breakpoints and can be
248 (re-)enabled.
249
250enable [*bpnumber* [*bpnumber ...*]]
251 Enables the breakpoints specified.
252
253ignore *bpnumber* [*count*]
254 Sets the ignore count for the given breakpoint number. If count is omitted, the
255 ignore count is set to 0. A breakpoint becomes active when the ignore count is
256 zero. When non-zero, the count is decremented each time the breakpoint is
257 reached and the breakpoint is not disabled and any associated condition
258 evaluates to true.
259
260condition *bpnumber* [*condition*]
261 Condition is an expression which must evaluate to true before the breakpoint is
262 honored. If condition is absent, any existing condition is removed; i.e., the
263 breakpoint is made unconditional.
264
265commands [*bpnumber*]
266 Specify a list of commands for breakpoint number *bpnumber*. The commands
267 themselves appear on the following lines. Type a line containing just 'end' to
268 terminate the commands. An example::
269
270 (Pdb) commands 1
271 (com) print some_variable
272 (com) end
273 (Pdb)
274
275 To remove all commands from a breakpoint, type commands and follow it
276 immediately with end; that is, give no commands.
277
278 With no *bpnumber* argument, commands refers to the last breakpoint set.
279
280 You can use breakpoint commands to start your program up again. Simply use the
281 continue command, or step, or any other command that resumes execution.
282
283 Specifying any command resuming execution (currently continue, step, next,
284 return, jump, quit and their abbreviations) terminates the command list (as if
285 that command was immediately followed by end). This is because any time you
Georg Brandl9afde1c2007-11-01 20:32:30 +0000286 resume execution (even with a simple next or step), you may encounter another
Georg Brandl116aa622007-08-15 14:28:22 +0000287 breakpoint--which could have its own command list, leading to ambiguities about
288 which list to execute.
289
290 If you use the 'silent' command in the command list, the usual message about
291 stopping at a breakpoint is not printed. This may be desirable for breakpoints
292 that are to print a specific message and then continue. If none of the other
293 commands print anything, you see no sign that the breakpoint was reached.
294
Georg Brandl116aa622007-08-15 14:28:22 +0000295s(tep)
296 Execute the current line, stop at the first possible occasion (either in a
297 function that is called or on the next line in the current function).
298
299n(ext)
300 Continue execution until the next line in the current function is reached or it
301 returns. (The difference between ``next`` and ``step`` is that ``step`` stops
302 inside a called function, while ``next`` executes called functions at (nearly)
303 full speed, only stopping at the next line in the current function.)
304
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000305unt(il)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000306 Continue execution until the line with the line number greater than the
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000307 current one is reached or when returning from current frame.
308
Georg Brandl116aa622007-08-15 14:28:22 +0000309r(eturn)
310 Continue execution until the current function returns.
311
312c(ont(inue))
313 Continue execution, only stop when a breakpoint is encountered.
314
315j(ump) *lineno*
316 Set the next line that will be executed. Only available in the bottom-most
317 frame. This lets you jump back and execute code again, or jump forward to skip
318 code that you don't want to run.
319
320 It should be noted that not all jumps are allowed --- for instance it is not
321 possible to jump into the middle of a :keyword:`for` loop or out of a
322 :keyword:`finally` clause.
323
Guido van Rossum61e21b52007-08-20 19:06:03 +0000324l(ist) [*first*\ [, *last*]]
Georg Brandl116aa622007-08-15 14:28:22 +0000325 List source code for the current file. Without arguments, list 11 lines around
326 the current line or continue the previous listing. With one argument, list 11
327 lines around at that line. With two arguments, list the given range; if the
328 second argument is less than the first, it is interpreted as a count.
329
330a(rgs)
331 Print the argument list of the current function.
332
Georg Brandlc9879242007-09-04 07:07:56 +0000333p(rint) *expression*
Georg Brandl116aa622007-08-15 14:28:22 +0000334 Evaluate the *expression* in the current context and print its value.
335
Georg Brandl116aa622007-08-15 14:28:22 +0000336pp *expression*
337 Like the ``p`` command, except the value of the expression is pretty-printed
338 using the :mod:`pprint` module.
339
340alias [*name* [command]]
341 Creates an alias called *name* that executes *command*. The command must *not*
342 be enclosed in quotes. Replaceable parameters can be indicated by ``%1``,
343 ``%2``, and so on, while ``%*`` is replaced by all the parameters. If no
344 command is given, the current alias for *name* is shown. If no arguments are
345 given, all aliases are listed.
346
347 Aliases may be nested and can contain anything that can be legally typed at the
348 pdb prompt. Note that internal pdb commands *can* be overridden by aliases.
349 Such a command is then hidden until the alias is removed. Aliasing is
350 recursively applied to the first word of the command line; all other words in
351 the line are left alone.
352
353 As an example, here are two useful aliases (especially when placed in the
354 :file:`.pdbrc` file)::
355
356 #Print instance variables (usage "pi classInst")
Georg Brandlc9879242007-09-04 07:07:56 +0000357 alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])
Georg Brandl116aa622007-08-15 14:28:22 +0000358 #Print instance variables in self
359 alias ps pi self
360
361unalias *name*
362 Deletes the specified alias.
363
Guido van Rossum61e21b52007-08-20 19:06:03 +0000364[!]\ *statement*
Georg Brandl116aa622007-08-15 14:28:22 +0000365 Execute the (one-line) *statement* in the context of the current stack frame.
366 The exclamation point can be omitted unless the first word of the statement
367 resembles a debugger command. To set a global variable, you can prefix the
368 assignment command with a ``global`` command on the same line, e.g.::
369
370 (Pdb) global list_options; list_options = ['-l']
371 (Pdb)
372
373run [*args* ...]
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000374 Restart the debugged Python program. If an argument is supplied, it is split
Georg Brandl116aa622007-08-15 14:28:22 +0000375 with "shlex" and the result is used as the new sys.argv. History, breakpoints,
376 actions and debugger options are preserved. "restart" is an alias for "run".
377
Georg Brandl116aa622007-08-15 14:28:22 +0000378q(uit)
379 Quit from the debugger. The program being executed is aborted.
Georg Brandl243ad662009-05-05 09:00:19 +0000380
381
382.. rubric:: Footnotes
383
384.. [1] Whether a frame is considered to originate in a certain module
385 is determined by the ``__name__`` in the frame globals.