blob: 7f2197ec3069d168e4522bec8a0035b2906cbee5 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2.. _debugger:
3
Georg Brandl00014222007-09-12 18:03:51 +00004:mod:`pdb` --- The Python Debugger
5==================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00006
7.. module:: pdb
8 :synopsis: The Python debugger for interactive interpreters.
9
10
11.. index:: single: debugging
12
13The module :mod:`pdb` defines an interactive source code debugger for Python
14programs. It supports setting (conditional) breakpoints and single stepping at
15the source line level, inspection of stack frames, source code listing, and
16evaluation of arbitrary Python code in the context of any stack frame. It also
17supports post-mortem debugging and can be called under program control.
18
19.. index::
20 single: Pdb (class in pdb)
21 module: bdb
22 module: cmd
23
24The debugger is extensible --- it is actually defined as the class :class:`Pdb`.
25This is currently undocumented but easily understood by reading the source. The
Georg Brandl4c86cb32010-03-21 19:34:26 +000026extension interface uses the modules :mod:`bdb` and :mod:`cmd`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000027
28The debugger's prompt is ``(Pdb)``. Typical usage to run a program under control
29of the debugger is::
30
31 >>> import pdb
32 >>> import mymodule
33 >>> pdb.run('mymodule.test()')
34 > <string>(0)?()
35 (Pdb) continue
36 > <string>(1)?()
37 (Pdb) continue
38 NameError: 'spam'
39 > <string>(1)?()
Georg Brandl734373c2009-01-03 21:55:17 +000040 (Pdb)
Georg Brandl8ec7f652007-08-15 14:28:01 +000041
42:file:`pdb.py` can also be invoked as a script to debug other scripts. For
43example::
44
45 python -m pdb myscript.py
46
47When invoked as a script, pdb will automatically enter post-mortem debugging if
48the program being debugged exits abnormally. After post-mortem debugging (or
49after normal exit of the program), pdb will restart the program. Automatic
50restarting preserves pdb's state (such as breakpoints) and in most cases is more
51useful than quitting the debugger upon program's exit.
52
53.. versionadded:: 2.4
54 Restarting post-mortem behavior added.
55
Georg Brandl8a859452009-10-27 14:59:26 +000056The typical usage to break into the debugger from a running program is to
57insert ::
58
59 import pdb; pdb.set_trace()
60
61at the location you want to break into the debugger. You can then step through
62the code following this statement, and continue running without the debugger using
63the ``c`` command.
64
65The typical usage to inspect a crashed program is::
Georg Brandl8ec7f652007-08-15 14:28:01 +000066
67 >>> import pdb
68 >>> import mymodule
69 >>> mymodule.test()
70 Traceback (most recent call last):
71 File "<stdin>", line 1, in ?
72 File "./mymodule.py", line 4, in test
73 test2()
74 File "./mymodule.py", line 3, in test2
75 print spam
76 NameError: spam
77 >>> pdb.pm()
78 > ./mymodule.py(3)test2()
79 -> print spam
Georg Brandl734373c2009-01-03 21:55:17 +000080 (Pdb)
Georg Brandl8ec7f652007-08-15 14:28:01 +000081
82The module defines the following functions; each enters the debugger in a
83slightly different way:
84
85
86.. function:: run(statement[, globals[, locals]])
87
88 Execute the *statement* (given as a string) under debugger control. The
89 debugger prompt appears before any code is executed; you can set breakpoints and
90 type ``continue``, or you can step through the statement using ``step`` or
91 ``next`` (all these commands are explained below). The optional *globals* and
92 *locals* arguments specify the environment in which the code is executed; by
93 default the dictionary of the module :mod:`__main__` is used. (See the
94 explanation of the :keyword:`exec` statement or the :func:`eval` built-in
95 function.)
96
97
98.. function:: runeval(expression[, globals[, locals]])
99
100 Evaluate the *expression* (given as a string) under debugger control. When
101 :func:`runeval` returns, it returns the value of the expression. Otherwise this
102 function is similar to :func:`run`.
103
104
105.. function:: runcall(function[, argument, ...])
106
107 Call the *function* (a function or method object, not a string) with the given
108 arguments. When :func:`runcall` returns, it returns whatever the function call
109 returned. The debugger prompt appears as soon as the function is entered.
110
111
112.. function:: set_trace()
113
114 Enter the debugger at the calling stack frame. This is useful to hard-code a
115 breakpoint at a given point in a program, even if the code is not otherwise
116 being debugged (e.g. when an assertion fails).
117
118
Facundo Batistac54aec12008-03-08 16:50:27 +0000119.. function:: post_mortem([traceback])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000120
Georg Brandl734373c2009-01-03 21:55:17 +0000121 Enter post-mortem debugging of the given *traceback* object. If no
Facundo Batistac54aec12008-03-08 16:50:27 +0000122 *traceback* is given, it uses the one of the exception that is currently
123 being handled (an exception must be being handled if the default is to be
124 used).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000125
126
127.. function:: pm()
128
129 Enter post-mortem debugging of the traceback found in ``sys.last_traceback``.
130
131
132.. _debugger-commands:
133
134Debugger Commands
135=================
136
137The debugger recognizes the following commands. Most commands can be
138abbreviated to one or two letters; e.g. ``h(elp)`` means that either ``h`` or
139``help`` can be used to enter the help command (but not ``he`` or ``hel``, nor
140``H`` or ``Help`` or ``HELP``). Arguments to commands must be separated by
141whitespace (spaces or tabs). Optional arguments are enclosed in square brackets
142(``[]``) in the command syntax; the square brackets must not be typed.
143Alternatives in the command syntax are separated by a vertical bar (``|``).
144
145Entering a blank line repeats the last command entered. Exception: if the last
146command was a ``list`` command, the next 11 lines are listed.
147
148Commands that the debugger doesn't recognize are assumed to be Python statements
149and are executed in the context of the program being debugged. Python
150statements can also be prefixed with an exclamation point (``!``). This is a
151powerful way to inspect the program being debugged; it is even possible to
152change a variable or call a function. When an exception occurs in such a
153statement, the exception name is printed but the debugger's state is not
154changed.
155
156Multiple commands may be entered on a single line, separated by ``;;``. (A
157single ``;`` is not used as it is the separator for multiple commands in a line
158that is passed to the Python parser.) No intelligence is applied to separating
159the commands; the input is split at the first ``;;`` pair, even if it is in the
160middle of a quoted string.
161
162The debugger supports aliases. Aliases can have parameters which allows one a
163certain level of adaptability to the context under examination.
164
165.. index::
166 pair: .pdbrc; file
167 triple: debugger; configuration; file
168
169If a file :file:`.pdbrc` exists in the user's home directory or in the current
170directory, it is read in and executed as if it had been typed at the debugger
171prompt. This is particularly useful for aliases. If both files exist, the one
172in the home directory is read first and aliases defined there can be overridden
173by the local file.
174
175h(elp) [*command*]
176 Without argument, print the list of available commands. With a *command* as
177 argument, print help about that command. ``help pdb`` displays the full
178 documentation file; if the environment variable :envvar:`PAGER` is defined, the
179 file is piped through that command instead. Since the *command* argument must
180 be an identifier, ``help exec`` must be entered to get help on the ``!``
181 command.
182
183w(here)
184 Print a stack trace, with the most recent frame at the bottom. An arrow
185 indicates the current frame, which determines the context of most commands.
186
187d(own)
188 Move the current frame one level down in the stack trace (to a newer frame).
189
190u(p)
191 Move the current frame one level up in the stack trace (to an older frame).
192
Georg Brandl3f8fbf02007-08-18 06:05:56 +0000193b(reak) [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000194 With a *lineno* argument, set a break there in the current file. With a
195 *function* argument, set a break at the first executable statement within that
196 function. The line number may be prefixed with a filename and a colon, to
197 specify a breakpoint in another file (probably one that hasn't been loaded yet).
198 The file is searched on ``sys.path``. Note that each breakpoint is assigned a
199 number to which all the other breakpoint commands refer.
200
201 If a second argument is present, it is an expression which must evaluate to true
202 before the breakpoint is honored.
203
204 Without argument, list all breaks, including for each breakpoint, the number of
205 times that breakpoint has been hit, the current ignore count, and the associated
206 condition if any.
207
Georg Brandl3f8fbf02007-08-18 06:05:56 +0000208tbreak [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000209 Temporary breakpoint, which is removed automatically when it is first hit. The
210 arguments are the same as break.
211
212cl(ear) [*bpnumber* [*bpnumber ...*]]
213 With a space separated list of breakpoint numbers, clear those breakpoints.
214 Without argument, clear all breaks (but first ask confirmation).
215
216disable [*bpnumber* [*bpnumber ...*]]
217 Disables the breakpoints given as a space separated list of breakpoint numbers.
218 Disabling a breakpoint means it cannot cause the program to stop execution, but
219 unlike clearing a breakpoint, it remains in the list of breakpoints and can be
220 (re-)enabled.
221
222enable [*bpnumber* [*bpnumber ...*]]
223 Enables the breakpoints specified.
224
225ignore *bpnumber* [*count*]
226 Sets the ignore count for the given breakpoint number. If count is omitted, the
227 ignore count is set to 0. A breakpoint becomes active when the ignore count is
228 zero. When non-zero, the count is decremented each time the breakpoint is
229 reached and the breakpoint is not disabled and any associated condition
230 evaluates to true.
231
232condition *bpnumber* [*condition*]
233 Condition is an expression which must evaluate to true before the breakpoint is
234 honored. If condition is absent, any existing condition is removed; i.e., the
235 breakpoint is made unconditional.
236
237commands [*bpnumber*]
238 Specify a list of commands for breakpoint number *bpnumber*. The commands
239 themselves appear on the following lines. Type a line containing just 'end' to
240 terminate the commands. An example::
241
242 (Pdb) commands 1
243 (com) print some_variable
244 (com) end
245 (Pdb)
246
247 To remove all commands from a breakpoint, type commands and follow it
248 immediately with end; that is, give no commands.
249
250 With no *bpnumber* argument, commands refers to the last breakpoint set.
251
252 You can use breakpoint commands to start your program up again. Simply use the
253 continue command, or step, or any other command that resumes execution.
254
255 Specifying any command resuming execution (currently continue, step, next,
256 return, jump, quit and their abbreviations) terminates the command list (as if
257 that command was immediately followed by end). This is because any time you
Andrew M. Kuchling9c906352007-09-24 23:45:51 +0000258 resume execution (even with a simple next or step), you may encounter another
Georg Brandl8ec7f652007-08-15 14:28:01 +0000259 breakpoint--which could have its own command list, leading to ambiguities about
260 which list to execute.
261
262 If you use the 'silent' command in the command list, the usual message about
263 stopping at a breakpoint is not printed. This may be desirable for breakpoints
264 that are to print a specific message and then continue. If none of the other
265 commands print anything, you see no sign that the breakpoint was reached.
266
267 .. versionadded:: 2.5
268
269s(tep)
270 Execute the current line, stop at the first possible occasion (either in a
271 function that is called or on the next line in the current function).
272
273n(ext)
274 Continue execution until the next line in the current function is reached or it
275 returns. (The difference between ``next`` and ``step`` is that ``step`` stops
276 inside a called function, while ``next`` executes called functions at (nearly)
277 full speed, only stopping at the next line in the current function.)
278
Benjamin Peterson98353942008-05-11 14:13:25 +0000279unt(il)
Andrew M. Kuchlingb20df9a2009-04-03 21:56:36 +0000280 Continue execution until the line with the line number greater than the
Georg Brandl9020ff82008-05-11 14:17:13 +0000281 current one is reached or when returning from current frame.
Benjamin Peterson98353942008-05-11 14:13:25 +0000282
283 .. versionadded:: 2.6
284
Georg Brandl8ec7f652007-08-15 14:28:01 +0000285r(eturn)
286 Continue execution until the current function returns.
287
288c(ont(inue))
289 Continue execution, only stop when a breakpoint is encountered.
290
291j(ump) *lineno*
292 Set the next line that will be executed. Only available in the bottom-most
293 frame. This lets you jump back and execute code again, or jump forward to skip
294 code that you don't want to run.
295
296 It should be noted that not all jumps are allowed --- for instance it is not
297 possible to jump into the middle of a :keyword:`for` loop or out of a
298 :keyword:`finally` clause.
299
Georg Brandl3f8fbf02007-08-18 06:05:56 +0000300l(ist) [*first*\ [, *last*]]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000301 List source code for the current file. Without arguments, list 11 lines around
302 the current line or continue the previous listing. With one argument, list 11
303 lines around at that line. With two arguments, list the given range; if the
304 second argument is less than the first, it is interpreted as a count.
305
306a(rgs)
307 Print the argument list of the current function.
308
309p *expression*
310 Evaluate the *expression* in the current context and print its value.
311
312 .. note::
313
314 ``print`` can also be used, but is not a debugger command --- this executes the
315 Python :keyword:`print` statement.
316
317pp *expression*
318 Like the ``p`` command, except the value of the expression is pretty-printed
319 using the :mod:`pprint` module.
320
321alias [*name* [command]]
322 Creates an alias called *name* that executes *command*. The command must *not*
323 be enclosed in quotes. Replaceable parameters can be indicated by ``%1``,
324 ``%2``, and so on, while ``%*`` is replaced by all the parameters. If no
325 command is given, the current alias for *name* is shown. If no arguments are
326 given, all aliases are listed.
327
328 Aliases may be nested and can contain anything that can be legally typed at the
329 pdb prompt. Note that internal pdb commands *can* be overridden by aliases.
330 Such a command is then hidden until the alias is removed. Aliasing is
331 recursively applied to the first word of the command line; all other words in
332 the line are left alone.
333
334 As an example, here are two useful aliases (especially when placed in the
335 :file:`.pdbrc` file)::
336
337 #Print instance variables (usage "pi classInst")
338 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
339 #Print instance variables in self
340 alias ps pi self
341
342unalias *name*
343 Deletes the specified alias.
344
Georg Brandl3f8fbf02007-08-18 06:05:56 +0000345[!]\ *statement*
Georg Brandl8ec7f652007-08-15 14:28:01 +0000346 Execute the (one-line) *statement* in the context of the current stack frame.
347 The exclamation point can be omitted unless the first word of the statement
348 resembles a debugger command. To set a global variable, you can prefix the
349 assignment command with a ``global`` command on the same line, e.g.::
350
351 (Pdb) global list_options; list_options = ['-l']
352 (Pdb)
353
354run [*args* ...]
Ezio Melotti2f4f2c12009-12-19 22:59:01 +0000355 Restart the debugged Python program. If an argument is supplied, it is split
Georg Brandl8ec7f652007-08-15 14:28:01 +0000356 with "shlex" and the result is used as the new sys.argv. History, breakpoints,
357 actions and debugger options are preserved. "restart" is an alias for "run".
358
359 .. versionadded:: 2.6
360
361q(uit)
362 Quit from the debugger. The program being executed is aborted.