blob: 96b524daf10c99001cf935c935a671cfffa58d24 [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
25extension interface uses the modules :mod:`bdb` (undocumented) and :mod:`cmd`.
26
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
58the code following this statement, and continue running without debugger using
59the ``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
213d(own)
214 Move the current frame one level down in the stack trace (to a newer frame).
215
216u(p)
217 Move the current frame one level up in the stack trace (to an older frame).
218
Guido van Rossum61e21b52007-08-20 19:06:03 +0000219b(reak) [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
Georg Brandl116aa622007-08-15 14:28:22 +0000220 With a *lineno* argument, set a break there in the current file. With a
221 *function* argument, set a break at the first executable statement within that
222 function. The line number may be prefixed with a filename and a colon, to
223 specify a breakpoint in another file (probably one that hasn't been loaded yet).
224 The file is searched on ``sys.path``. Note that each breakpoint is assigned a
225 number to which all the other breakpoint commands refer.
226
227 If a second argument is present, it is an expression which must evaluate to true
228 before the breakpoint is honored.
229
230 Without argument, list all breaks, including for each breakpoint, the number of
231 times that breakpoint has been hit, the current ignore count, and the associated
232 condition if any.
233
Guido van Rossum61e21b52007-08-20 19:06:03 +0000234tbreak [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
Georg Brandl116aa622007-08-15 14:28:22 +0000235 Temporary breakpoint, which is removed automatically when it is first hit. The
236 arguments are the same as break.
237
238cl(ear) [*bpnumber* [*bpnumber ...*]]
239 With a space separated list of breakpoint numbers, clear those breakpoints.
240 Without argument, clear all breaks (but first ask confirmation).
241
242disable [*bpnumber* [*bpnumber ...*]]
243 Disables the breakpoints given as a space separated list of breakpoint numbers.
244 Disabling a breakpoint means it cannot cause the program to stop execution, but
245 unlike clearing a breakpoint, it remains in the list of breakpoints and can be
246 (re-)enabled.
247
248enable [*bpnumber* [*bpnumber ...*]]
249 Enables the breakpoints specified.
250
251ignore *bpnumber* [*count*]
252 Sets the ignore count for the given breakpoint number. If count is omitted, the
253 ignore count is set to 0. A breakpoint becomes active when the ignore count is
254 zero. When non-zero, the count is decremented each time the breakpoint is
255 reached and the breakpoint is not disabled and any associated condition
256 evaluates to true.
257
258condition *bpnumber* [*condition*]
259 Condition is an expression which must evaluate to true before the breakpoint is
260 honored. If condition is absent, any existing condition is removed; i.e., the
261 breakpoint is made unconditional.
262
263commands [*bpnumber*]
264 Specify a list of commands for breakpoint number *bpnumber*. The commands
265 themselves appear on the following lines. Type a line containing just 'end' to
266 terminate the commands. An example::
267
268 (Pdb) commands 1
269 (com) print some_variable
270 (com) end
271 (Pdb)
272
273 To remove all commands from a breakpoint, type commands and follow it
274 immediately with end; that is, give no commands.
275
276 With no *bpnumber* argument, commands refers to the last breakpoint set.
277
278 You can use breakpoint commands to start your program up again. Simply use the
279 continue command, or step, or any other command that resumes execution.
280
281 Specifying any command resuming execution (currently continue, step, next,
282 return, jump, quit and their abbreviations) terminates the command list (as if
283 that command was immediately followed by end). This is because any time you
Georg Brandl9afde1c2007-11-01 20:32:30 +0000284 resume execution (even with a simple next or step), you may encounter another
Georg Brandl116aa622007-08-15 14:28:22 +0000285 breakpoint--which could have its own command list, leading to ambiguities about
286 which list to execute.
287
288 If you use the 'silent' command in the command list, the usual message about
289 stopping at a breakpoint is not printed. This may be desirable for breakpoints
290 that are to print a specific message and then continue. If none of the other
291 commands print anything, you see no sign that the breakpoint was reached.
292
Georg Brandl116aa622007-08-15 14:28:22 +0000293s(tep)
294 Execute the current line, stop at the first possible occasion (either in a
295 function that is called or on the next line in the current function).
296
297n(ext)
298 Continue execution until the next line in the current function is reached or it
299 returns. (The difference between ``next`` and ``step`` is that ``step`` stops
300 inside a called function, while ``next`` executes called functions at (nearly)
301 full speed, only stopping at the next line in the current function.)
302
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000303unt(il)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000304 Continue execution until the line with the line number greater than the
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000305 current one is reached or when returning from current frame.
306
Georg Brandl116aa622007-08-15 14:28:22 +0000307r(eturn)
308 Continue execution until the current function returns.
309
310c(ont(inue))
311 Continue execution, only stop when a breakpoint is encountered.
312
313j(ump) *lineno*
314 Set the next line that will be executed. Only available in the bottom-most
315 frame. This lets you jump back and execute code again, or jump forward to skip
316 code that you don't want to run.
317
318 It should be noted that not all jumps are allowed --- for instance it is not
319 possible to jump into the middle of a :keyword:`for` loop or out of a
320 :keyword:`finally` clause.
321
Guido van Rossum61e21b52007-08-20 19:06:03 +0000322l(ist) [*first*\ [, *last*]]
Georg Brandl116aa622007-08-15 14:28:22 +0000323 List source code for the current file. Without arguments, list 11 lines around
324 the current line or continue the previous listing. With one argument, list 11
325 lines around at that line. With two arguments, list the given range; if the
326 second argument is less than the first, it is interpreted as a count.
327
328a(rgs)
329 Print the argument list of the current function.
330
Georg Brandlc9879242007-09-04 07:07:56 +0000331p(rint) *expression*
Georg Brandl116aa622007-08-15 14:28:22 +0000332 Evaluate the *expression* in the current context and print its value.
333
Georg Brandl116aa622007-08-15 14:28:22 +0000334pp *expression*
335 Like the ``p`` command, except the value of the expression is pretty-printed
336 using the :mod:`pprint` module.
337
338alias [*name* [command]]
339 Creates an alias called *name* that executes *command*. The command must *not*
340 be enclosed in quotes. Replaceable parameters can be indicated by ``%1``,
341 ``%2``, and so on, while ``%*`` is replaced by all the parameters. If no
342 command is given, the current alias for *name* is shown. If no arguments are
343 given, all aliases are listed.
344
345 Aliases may be nested and can contain anything that can be legally typed at the
346 pdb prompt. Note that internal pdb commands *can* be overridden by aliases.
347 Such a command is then hidden until the alias is removed. Aliasing is
348 recursively applied to the first word of the command line; all other words in
349 the line are left alone.
350
351 As an example, here are two useful aliases (especially when placed in the
352 :file:`.pdbrc` file)::
353
354 #Print instance variables (usage "pi classInst")
Georg Brandlc9879242007-09-04 07:07:56 +0000355 alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])
Georg Brandl116aa622007-08-15 14:28:22 +0000356 #Print instance variables in self
357 alias ps pi self
358
359unalias *name*
360 Deletes the specified alias.
361
Guido van Rossum61e21b52007-08-20 19:06:03 +0000362[!]\ *statement*
Georg Brandl116aa622007-08-15 14:28:22 +0000363 Execute the (one-line) *statement* in the context of the current stack frame.
364 The exclamation point can be omitted unless the first word of the statement
365 resembles a debugger command. To set a global variable, you can prefix the
366 assignment command with a ``global`` command on the same line, e.g.::
367
368 (Pdb) global list_options; list_options = ['-l']
369 (Pdb)
370
371run [*args* ...]
Georg Brandl9afde1c2007-11-01 20:32:30 +0000372 Restart the debugged python program. If an argument is supplied, it is split
Georg Brandl116aa622007-08-15 14:28:22 +0000373 with "shlex" and the result is used as the new sys.argv. History, breakpoints,
374 actions and debugger options are preserved. "restart" is an alias for "run".
375
Georg Brandl116aa622007-08-15 14:28:22 +0000376q(uit)
377 Quit from the debugger. The program being executed is aborted.
Georg Brandl243ad662009-05-05 09:00:19 +0000378
379
380.. rubric:: Footnotes
381
382.. [1] Whether a frame is considered to originate in a certain module
383 is determined by the ``__name__`` in the frame globals.