blob: a475099d6a57b740a102f09c1b399a17ca2b8781 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001.. _debugger:
2
Georg Brandl00014222007-09-12 18:03:51 +00003:mod:`pdb` --- The Python Debugger
4==================================
Georg Brandl8ec7f652007-08-15 14:28:01 +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 Brandl118c5572010-03-21 09:01:27 +000025extension interface uses the modules :mod:`bdb` and :mod:`cmd`.
Georg Brandl8ec7f652007-08-15 14:28:01 +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 Brandlc62ef8b2009-01-03 20:55:06 +000039 (Pdb)
Georg Brandl8ec7f652007-08-15 14:28:01 +000040
41:file:`pdb.py` can also be invoked as a script to debug other scripts. For
42example::
43
44 python -m pdb myscript.py
45
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
52.. versionadded:: 2.4
53 Restarting post-mortem behavior added.
54
Georg Brandl4d4313d2009-05-05 08:54:11 +000055The typical usage to break into the debugger from a running program is to
56insert ::
57
58 import pdb; pdb.set_trace()
59
60at the location you want to break into the debugger. You can then step through
Andrew M. Kuchling3fab0402009-10-05 21:24:20 +000061the code following this statement, and continue running without the debugger using
Georg Brandl4d4313d2009-05-05 08:54:11 +000062the ``c`` command.
63
64The typical usage to inspect a crashed program is::
Georg Brandl8ec7f652007-08-15 14:28:01 +000065
66 >>> import pdb
67 >>> import mymodule
68 >>> mymodule.test()
69 Traceback (most recent call last):
70 File "<stdin>", line 1, in ?
71 File "./mymodule.py", line 4, in test
72 test2()
73 File "./mymodule.py", line 3, in test2
74 print spam
75 NameError: spam
76 >>> pdb.pm()
77 > ./mymodule.py(3)test2()
78 -> print spam
Georg Brandlc62ef8b2009-01-03 20:55:06 +000079 (Pdb)
Georg Brandl8ec7f652007-08-15 14:28:01 +000080
Georg Brandl4d4313d2009-05-05 08:54:11 +000081
Georg Brandl8ec7f652007-08-15 14:28:01 +000082The module defines the following functions; each enters the debugger in a
83slightly different way:
84
Georg Brandl8ec7f652007-08-15 14:28:01 +000085.. function:: run(statement[, globals[, locals]])
86
87 Execute the *statement* (given as a string) under debugger control. The
88 debugger prompt appears before any code is executed; you can set breakpoints and
89 type ``continue``, or you can step through the statement using ``step`` or
90 ``next`` (all these commands are explained below). The optional *globals* and
91 *locals* arguments specify the environment in which the code is executed; by
92 default the dictionary of the module :mod:`__main__` is used. (See the
93 explanation of the :keyword:`exec` statement or the :func:`eval` built-in
94 function.)
95
96
97.. function:: runeval(expression[, globals[, locals]])
98
99 Evaluate the *expression* (given as a string) under debugger control. When
100 :func:`runeval` returns, it returns the value of the expression. Otherwise this
101 function is similar to :func:`run`.
102
103
104.. function:: runcall(function[, argument, ...])
105
106 Call the *function* (a function or method object, not a string) with the given
107 arguments. When :func:`runcall` returns, it returns whatever the function call
108 returned. The debugger prompt appears as soon as the function is entered.
109
110
111.. function:: set_trace()
112
113 Enter the debugger at the calling stack frame. This is useful to hard-code a
114 breakpoint at a given point in a program, even if the code is not otherwise
115 being debugged (e.g. when an assertion fails).
116
117
Facundo Batistac54aec12008-03-08 16:50:27 +0000118.. function:: post_mortem([traceback])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000119
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000120 Enter post-mortem debugging of the given *traceback* object. If no
Facundo Batistac54aec12008-03-08 16:50:27 +0000121 *traceback* is given, it uses the one of the exception that is currently
122 being handled (an exception must be being handled if the default is to be
123 used).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000124
125
126.. function:: pm()
127
Georg Brandl4d4313d2009-05-05 08:54:11 +0000128 Enter post-mortem debugging of the traceback found in
129 :data:`sys.last_traceback`.
130
131
Eli Benderskyf274eea2011-01-14 07:50:27 +0000132The ``run*`` functions and :func:`set_trace` are aliases for instantiating the
Georg Brandl4d4313d2009-05-05 08:54:11 +0000133:class:`Pdb` class and calling the method of the same name. If you want to
134access further features, you have to do this yourself:
135
136.. class:: Pdb(completekey='tab', stdin=None, stdout=None, skip=None)
137
138 :class:`Pdb` is the debugger class.
139
140 The *completekey*, *stdin* and *stdout* arguments are passed to the
141 underlying :class:`cmd.Cmd` class; see the description there.
142
143 The *skip* argument, if given, must be an iterable of glob-style module name
144 patterns. The debugger will not step into frames that originate in a module
145 that matches one of these patterns. [1]_
146
147 Example call to enable tracing with *skip*::
148
149 import pdb; pdb.Pdb(skip=['django.*']).set_trace()
150
151 .. versionadded:: 2.7
152 The *skip* argument.
153
154 .. method:: run(statement[, globals[, locals]])
155 runeval(expression[, globals[, locals]])
156 runcall(function[, argument, ...])
157 set_trace()
158
159 See the documentation for the functions explained above.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000160
161
162.. _debugger-commands:
163
164Debugger Commands
165=================
166
167The debugger recognizes the following commands. Most commands can be
168abbreviated to one or two letters; e.g. ``h(elp)`` means that either ``h`` or
169``help`` can be used to enter the help command (but not ``he`` or ``hel``, nor
170``H`` or ``Help`` or ``HELP``). Arguments to commands must be separated by
171whitespace (spaces or tabs). Optional arguments are enclosed in square brackets
172(``[]``) in the command syntax; the square brackets must not be typed.
173Alternatives in the command syntax are separated by a vertical bar (``|``).
174
175Entering a blank line repeats the last command entered. Exception: if the last
176command was a ``list`` command, the next 11 lines are listed.
177
178Commands that the debugger doesn't recognize are assumed to be Python statements
179and are executed in the context of the program being debugged. Python
180statements can also be prefixed with an exclamation point (``!``). This is a
181powerful way to inspect the program being debugged; it is even possible to
182change a variable or call a function. When an exception occurs in such a
183statement, the exception name is printed but the debugger's state is not
184changed.
185
186Multiple commands may be entered on a single line, separated by ``;;``. (A
187single ``;`` is not used as it is the separator for multiple commands in a line
188that is passed to the Python parser.) No intelligence is applied to separating
189the commands; the input is split at the first ``;;`` pair, even if it is in the
190middle of a quoted string.
191
192The debugger supports aliases. Aliases can have parameters which allows one a
193certain level of adaptability to the context under examination.
194
195.. index::
196 pair: .pdbrc; file
197 triple: debugger; configuration; file
198
199If a file :file:`.pdbrc` exists in the user's home directory or in the current
200directory, it is read in and executed as if it had been typed at the debugger
201prompt. This is particularly useful for aliases. If both files exist, the one
202in the home directory is read first and aliases defined there can be overridden
203by the local file.
204
205h(elp) [*command*]
206 Without argument, print the list of available commands. With a *command* as
207 argument, print help about that command. ``help pdb`` displays the full
208 documentation file; if the environment variable :envvar:`PAGER` is defined, the
209 file is piped through that command instead. Since the *command* argument must
210 be an identifier, ``help exec`` must be entered to get help on the ``!``
211 command.
212
213w(here)
214 Print a stack trace, with the most recent frame at the bottom. An arrow
215 indicates the current frame, which determines the context of most commands.
216
217d(own)
218 Move the current frame one level down in the stack trace (to a newer frame).
219
220u(p)
221 Move the current frame one level up in the stack trace (to an older frame).
222
Georg Brandl3f8fbf02007-08-18 06:05:56 +0000223b(reak) [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000224 With a *lineno* argument, set a break there in the current file. With a
225 *function* argument, set a break at the first executable statement within that
226 function. The line number may be prefixed with a filename and a colon, to
227 specify a breakpoint in another file (probably one that hasn't been loaded yet).
228 The file is searched on ``sys.path``. Note that each breakpoint is assigned a
229 number to which all the other breakpoint commands refer.
230
231 If a second argument is present, it is an expression which must evaluate to true
232 before the breakpoint is honored.
233
234 Without argument, list all breaks, including for each breakpoint, the number of
235 times that breakpoint has been hit, the current ignore count, and the associated
236 condition if any.
237
Georg Brandl3f8fbf02007-08-18 06:05:56 +0000238tbreak [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000239 Temporary breakpoint, which is removed automatically when it is first hit. The
240 arguments are the same as break.
241
Senthil Kumaran9a5897b2010-11-29 12:41:03 +0000242cl(ear) [*filename:lineno* | *bpnumber* [*bpnumber ...*]]
243 With a *filename:lineno* argument, clear all the breakpoints at this line.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000244 With a space separated list of breakpoint numbers, clear those breakpoints.
245 Without argument, clear all breaks (but first ask confirmation).
246
247disable [*bpnumber* [*bpnumber ...*]]
248 Disables the breakpoints given as a space separated list of breakpoint numbers.
249 Disabling a breakpoint means it cannot cause the program to stop execution, but
250 unlike clearing a breakpoint, it remains in the list of breakpoints and can be
251 (re-)enabled.
252
253enable [*bpnumber* [*bpnumber ...*]]
254 Enables the breakpoints specified.
255
256ignore *bpnumber* [*count*]
257 Sets the ignore count for the given breakpoint number. If count is omitted, the
258 ignore count is set to 0. A breakpoint becomes active when the ignore count is
259 zero. When non-zero, the count is decremented each time the breakpoint is
260 reached and the breakpoint is not disabled and any associated condition
261 evaluates to true.
262
263condition *bpnumber* [*condition*]
264 Condition is an expression which must evaluate to true before the breakpoint is
265 honored. If condition is absent, any existing condition is removed; i.e., the
266 breakpoint is made unconditional.
267
268commands [*bpnumber*]
269 Specify a list of commands for breakpoint number *bpnumber*. The commands
270 themselves appear on the following lines. Type a line containing just 'end' to
271 terminate the commands. An example::
272
273 (Pdb) commands 1
274 (com) print some_variable
275 (com) end
276 (Pdb)
277
278 To remove all commands from a breakpoint, type commands and follow it
279 immediately with end; that is, give no commands.
280
281 With no *bpnumber* argument, commands refers to the last breakpoint set.
282
283 You can use breakpoint commands to start your program up again. Simply use the
284 continue command, or step, or any other command that resumes execution.
285
286 Specifying any command resuming execution (currently continue, step, next,
287 return, jump, quit and their abbreviations) terminates the command list (as if
288 that command was immediately followed by end). This is because any time you
Andrew M. Kuchling9c906352007-09-24 23:45:51 +0000289 resume execution (even with a simple next or step), you may encounter another
Georg Brandl8ec7f652007-08-15 14:28:01 +0000290 breakpoint--which could have its own command list, leading to ambiguities about
291 which list to execute.
292
293 If you use the 'silent' command in the command list, the usual message about
294 stopping at a breakpoint is not printed. This may be desirable for breakpoints
295 that are to print a specific message and then continue. If none of the other
296 commands print anything, you see no sign that the breakpoint was reached.
297
298 .. versionadded:: 2.5
299
300s(tep)
301 Execute the current line, stop at the first possible occasion (either in a
302 function that is called or on the next line in the current function).
303
304n(ext)
305 Continue execution until the next line in the current function is reached or it
306 returns. (The difference between ``next`` and ``step`` is that ``step`` stops
307 inside a called function, while ``next`` executes called functions at (nearly)
308 full speed, only stopping at the next line in the current function.)
309
Benjamin Peterson98353942008-05-11 14:13:25 +0000310unt(il)
Andrew M. Kuchlinga178a692009-04-03 21:45:29 +0000311 Continue execution until the line with the line number greater than the
Georg Brandl9020ff82008-05-11 14:17:13 +0000312 current one is reached or when returning from current frame.
Benjamin Peterson98353942008-05-11 14:13:25 +0000313
314 .. versionadded:: 2.6
315
Georg Brandl8ec7f652007-08-15 14:28:01 +0000316r(eturn)
317 Continue execution until the current function returns.
318
319c(ont(inue))
320 Continue execution, only stop when a breakpoint is encountered.
321
322j(ump) *lineno*
323 Set the next line that will be executed. Only available in the bottom-most
324 frame. This lets you jump back and execute code again, or jump forward to skip
325 code that you don't want to run.
326
327 It should be noted that not all jumps are allowed --- for instance it is not
328 possible to jump into the middle of a :keyword:`for` loop or out of a
329 :keyword:`finally` clause.
330
Georg Brandl3f8fbf02007-08-18 06:05:56 +0000331l(ist) [*first*\ [, *last*]]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000332 List source code for the current file. Without arguments, list 11 lines around
333 the current line or continue the previous listing. With one argument, list 11
334 lines around at that line. With two arguments, list the given range; if the
335 second argument is less than the first, it is interpreted as a count.
336
337a(rgs)
338 Print the argument list of the current function.
339
340p *expression*
341 Evaluate the *expression* in the current context and print its value.
342
343 .. note::
344
345 ``print`` can also be used, but is not a debugger command --- this executes the
346 Python :keyword:`print` statement.
347
348pp *expression*
349 Like the ``p`` command, except the value of the expression is pretty-printed
350 using the :mod:`pprint` module.
351
352alias [*name* [command]]
353 Creates an alias called *name* that executes *command*. The command must *not*
354 be enclosed in quotes. Replaceable parameters can be indicated by ``%1``,
355 ``%2``, and so on, while ``%*`` is replaced by all the parameters. If no
356 command is given, the current alias for *name* is shown. If no arguments are
357 given, all aliases are listed.
358
359 Aliases may be nested and can contain anything that can be legally typed at the
360 pdb prompt. Note that internal pdb commands *can* be overridden by aliases.
361 Such a command is then hidden until the alias is removed. Aliasing is
362 recursively applied to the first word of the command line; all other words in
363 the line are left alone.
364
365 As an example, here are two useful aliases (especially when placed in the
366 :file:`.pdbrc` file)::
367
368 #Print instance variables (usage "pi classInst")
369 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
370 #Print instance variables in self
371 alias ps pi self
372
373unalias *name*
374 Deletes the specified alias.
375
Georg Brandl3f8fbf02007-08-18 06:05:56 +0000376[!]\ *statement*
Georg Brandl8ec7f652007-08-15 14:28:01 +0000377 Execute the (one-line) *statement* in the context of the current stack frame.
378 The exclamation point can be omitted unless the first word of the statement
379 resembles a debugger command. To set a global variable, you can prefix the
380 assignment command with a ``global`` command on the same line, e.g.::
381
382 (Pdb) global list_options; list_options = ['-l']
383 (Pdb)
384
385run [*args* ...]
Ezio Melotti062d2b52009-12-19 22:41:49 +0000386 Restart the debugged Python program. If an argument is supplied, it is split
Georg Brandl8ec7f652007-08-15 14:28:01 +0000387 with "shlex" and the result is used as the new sys.argv. History, breakpoints,
388 actions and debugger options are preserved. "restart" is an alias for "run".
389
390 .. versionadded:: 2.6
391
392q(uit)
393 Quit from the debugger. The program being executed is aborted.
Georg Brandl4d4313d2009-05-05 08:54:11 +0000394
395
396.. rubric:: Footnotes
397
398.. [1] Whether a frame is considered to originate in a certain module
399 is determined by the ``__name__`` in the frame globals.