blob: 2b28ae0ef52e7e5c9d6740f0e2a24079553b3b34 [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
26extension interface uses the modules :mod:`bdb` (undocumented) and :mod:`cmd`.
27
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)?()
40 (Pdb)
41
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
56Typical usage to inspect a crashed program is::
57
58 >>> import pdb
59 >>> import mymodule
60 >>> mymodule.test()
61 Traceback (most recent call last):
62 File "<stdin>", line 1, in ?
63 File "./mymodule.py", line 4, in test
64 test2()
65 File "./mymodule.py", line 3, in test2
66 print spam
67 NameError: spam
68 >>> pdb.pm()
69 > ./mymodule.py(3)test2()
70 -> print spam
71 (Pdb)
72
73The module defines the following functions; each enters the debugger in a
74slightly different way:
75
76
77.. function:: run(statement[, globals[, locals]])
78
79 Execute the *statement* (given as a string) under debugger control. The
80 debugger prompt appears before any code is executed; you can set breakpoints and
81 type ``continue``, or you can step through the statement using ``step`` or
82 ``next`` (all these commands are explained below). The optional *globals* and
83 *locals* arguments specify the environment in which the code is executed; by
84 default the dictionary of the module :mod:`__main__` is used. (See the
85 explanation of the :keyword:`exec` statement or the :func:`eval` built-in
86 function.)
87
88
89.. function:: runeval(expression[, globals[, locals]])
90
91 Evaluate the *expression* (given as a string) under debugger control. When
92 :func:`runeval` returns, it returns the value of the expression. Otherwise this
93 function is similar to :func:`run`.
94
95
96.. function:: runcall(function[, argument, ...])
97
98 Call the *function* (a function or method object, not a string) with the given
99 arguments. When :func:`runcall` returns, it returns whatever the function call
100 returned. The debugger prompt appears as soon as the function is entered.
101
102
103.. function:: set_trace()
104
105 Enter the debugger at the calling stack frame. This is useful to hard-code a
106 breakpoint at a given point in a program, even if the code is not otherwise
107 being debugged (e.g. when an assertion fails).
108
109
110.. function:: post_mortem(traceback)
111
112 Enter post-mortem debugging of the given *traceback* object.
113
114
115.. function:: pm()
116
117 Enter post-mortem debugging of the traceback found in ``sys.last_traceback``.
118
119
120.. _debugger-commands:
121
122Debugger Commands
123=================
124
125The debugger recognizes the following commands. Most commands can be
126abbreviated to one or two letters; e.g. ``h(elp)`` means that either ``h`` or
127``help`` can be used to enter the help command (but not ``he`` or ``hel``, nor
128``H`` or ``Help`` or ``HELP``). Arguments to commands must be separated by
129whitespace (spaces or tabs). Optional arguments are enclosed in square brackets
130(``[]``) in the command syntax; the square brackets must not be typed.
131Alternatives in the command syntax are separated by a vertical bar (``|``).
132
133Entering a blank line repeats the last command entered. Exception: if the last
134command was a ``list`` command, the next 11 lines are listed.
135
136Commands that the debugger doesn't recognize are assumed to be Python statements
137and are executed in the context of the program being debugged. Python
138statements can also be prefixed with an exclamation point (``!``). This is a
139powerful way to inspect the program being debugged; it is even possible to
140change a variable or call a function. When an exception occurs in such a
141statement, the exception name is printed but the debugger's state is not
142changed.
143
144Multiple commands may be entered on a single line, separated by ``;;``. (A
145single ``;`` is not used as it is the separator for multiple commands in a line
146that is passed to the Python parser.) No intelligence is applied to separating
147the commands; the input is split at the first ``;;`` pair, even if it is in the
148middle of a quoted string.
149
150The debugger supports aliases. Aliases can have parameters which allows one a
151certain level of adaptability to the context under examination.
152
153.. index::
154 pair: .pdbrc; file
155 triple: debugger; configuration; file
156
157If a file :file:`.pdbrc` exists in the user's home directory or in the current
158directory, it is read in and executed as if it had been typed at the debugger
159prompt. This is particularly useful for aliases. If both files exist, the one
160in the home directory is read first and aliases defined there can be overridden
161by the local file.
162
163h(elp) [*command*]
164 Without argument, print the list of available commands. With a *command* as
165 argument, print help about that command. ``help pdb`` displays the full
166 documentation file; if the environment variable :envvar:`PAGER` is defined, the
167 file is piped through that command instead. Since the *command* argument must
168 be an identifier, ``help exec`` must be entered to get help on the ``!``
169 command.
170
171w(here)
172 Print a stack trace, with the most recent frame at the bottom. An arrow
173 indicates the current frame, which determines the context of most commands.
174
175d(own)
176 Move the current frame one level down in the stack trace (to a newer frame).
177
178u(p)
179 Move the current frame one level up in the stack trace (to an older frame).
180
Georg Brandl3f8fbf02007-08-18 06:05:56 +0000181b(reak) [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182 With a *lineno* argument, set a break there in the current file. With a
183 *function* argument, set a break at the first executable statement within that
184 function. The line number may be prefixed with a filename and a colon, to
185 specify a breakpoint in another file (probably one that hasn't been loaded yet).
186 The file is searched on ``sys.path``. Note that each breakpoint is assigned a
187 number to which all the other breakpoint commands refer.
188
189 If a second argument is present, it is an expression which must evaluate to true
190 before the breakpoint is honored.
191
192 Without argument, list all breaks, including for each breakpoint, the number of
193 times that breakpoint has been hit, the current ignore count, and the associated
194 condition if any.
195
Georg Brandl3f8fbf02007-08-18 06:05:56 +0000196tbreak [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000197 Temporary breakpoint, which is removed automatically when it is first hit. The
198 arguments are the same as break.
199
200cl(ear) [*bpnumber* [*bpnumber ...*]]
201 With a space separated list of breakpoint numbers, clear those breakpoints.
202 Without argument, clear all breaks (but first ask confirmation).
203
204disable [*bpnumber* [*bpnumber ...*]]
205 Disables the breakpoints given as a space separated list of breakpoint numbers.
206 Disabling a breakpoint means it cannot cause the program to stop execution, but
207 unlike clearing a breakpoint, it remains in the list of breakpoints and can be
208 (re-)enabled.
209
210enable [*bpnumber* [*bpnumber ...*]]
211 Enables the breakpoints specified.
212
213ignore *bpnumber* [*count*]
214 Sets the ignore count for the given breakpoint number. If count is omitted, the
215 ignore count is set to 0. A breakpoint becomes active when the ignore count is
216 zero. When non-zero, the count is decremented each time the breakpoint is
217 reached and the breakpoint is not disabled and any associated condition
218 evaluates to true.
219
220condition *bpnumber* [*condition*]
221 Condition is an expression which must evaluate to true before the breakpoint is
222 honored. If condition is absent, any existing condition is removed; i.e., the
223 breakpoint is made unconditional.
224
225commands [*bpnumber*]
226 Specify a list of commands for breakpoint number *bpnumber*. The commands
227 themselves appear on the following lines. Type a line containing just 'end' to
228 terminate the commands. An example::
229
230 (Pdb) commands 1
231 (com) print some_variable
232 (com) end
233 (Pdb)
234
235 To remove all commands from a breakpoint, type commands and follow it
236 immediately with end; that is, give no commands.
237
238 With no *bpnumber* argument, commands refers to the last breakpoint set.
239
240 You can use breakpoint commands to start your program up again. Simply use the
241 continue command, or step, or any other command that resumes execution.
242
243 Specifying any command resuming execution (currently continue, step, next,
244 return, jump, quit and their abbreviations) terminates the command list (as if
245 that command was immediately followed by end). This is because any time you
Andrew M. Kuchling9c906352007-09-24 23:45:51 +0000246 resume execution (even with a simple next or step), you may encounter another
Georg Brandl8ec7f652007-08-15 14:28:01 +0000247 breakpoint--which could have its own command list, leading to ambiguities about
248 which list to execute.
249
250 If you use the 'silent' command in the command list, the usual message about
251 stopping at a breakpoint is not printed. This may be desirable for breakpoints
252 that are to print a specific message and then continue. If none of the other
253 commands print anything, you see no sign that the breakpoint was reached.
254
255 .. versionadded:: 2.5
256
257s(tep)
258 Execute the current line, stop at the first possible occasion (either in a
259 function that is called or on the next line in the current function).
260
261n(ext)
262 Continue execution until the next line in the current function is reached or it
263 returns. (The difference between ``next`` and ``step`` is that ``step`` stops
264 inside a called function, while ``next`` executes called functions at (nearly)
265 full speed, only stopping at the next line in the current function.)
266
267r(eturn)
268 Continue execution until the current function returns.
269
270c(ont(inue))
271 Continue execution, only stop when a breakpoint is encountered.
272
273j(ump) *lineno*
274 Set the next line that will be executed. Only available in the bottom-most
275 frame. This lets you jump back and execute code again, or jump forward to skip
276 code that you don't want to run.
277
278 It should be noted that not all jumps are allowed --- for instance it is not
279 possible to jump into the middle of a :keyword:`for` loop or out of a
280 :keyword:`finally` clause.
281
Georg Brandl3f8fbf02007-08-18 06:05:56 +0000282l(ist) [*first*\ [, *last*]]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283 List source code for the current file. Without arguments, list 11 lines around
284 the current line or continue the previous listing. With one argument, list 11
285 lines around at that line. With two arguments, list the given range; if the
286 second argument is less than the first, it is interpreted as a count.
287
288a(rgs)
289 Print the argument list of the current function.
290
291p *expression*
292 Evaluate the *expression* in the current context and print its value.
293
294 .. note::
295
296 ``print`` can also be used, but is not a debugger command --- this executes the
297 Python :keyword:`print` statement.
298
299pp *expression*
300 Like the ``p`` command, except the value of the expression is pretty-printed
301 using the :mod:`pprint` module.
302
303alias [*name* [command]]
304 Creates an alias called *name* that executes *command*. The command must *not*
305 be enclosed in quotes. Replaceable parameters can be indicated by ``%1``,
306 ``%2``, and so on, while ``%*`` is replaced by all the parameters. If no
307 command is given, the current alias for *name* is shown. If no arguments are
308 given, all aliases are listed.
309
310 Aliases may be nested and can contain anything that can be legally typed at the
311 pdb prompt. Note that internal pdb commands *can* be overridden by aliases.
312 Such a command is then hidden until the alias is removed. Aliasing is
313 recursively applied to the first word of the command line; all other words in
314 the line are left alone.
315
316 As an example, here are two useful aliases (especially when placed in the
317 :file:`.pdbrc` file)::
318
319 #Print instance variables (usage "pi classInst")
320 alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
321 #Print instance variables in self
322 alias ps pi self
323
324unalias *name*
325 Deletes the specified alias.
326
Georg Brandl3f8fbf02007-08-18 06:05:56 +0000327[!]\ *statement*
Georg Brandl8ec7f652007-08-15 14:28:01 +0000328 Execute the (one-line) *statement* in the context of the current stack frame.
329 The exclamation point can be omitted unless the first word of the statement
330 resembles a debugger command. To set a global variable, you can prefix the
331 assignment command with a ``global`` command on the same line, e.g.::
332
333 (Pdb) global list_options; list_options = ['-l']
334 (Pdb)
335
336run [*args* ...]
Andrew M. Kuchling9c906352007-09-24 23:45:51 +0000337 Restart the debugged python program. If an argument is supplied, it is split
Georg Brandl8ec7f652007-08-15 14:28:01 +0000338 with "shlex" and the result is used as the new sys.argv. History, breakpoints,
339 actions and debugger options are preserved. "restart" is an alias for "run".
340
341 .. versionadded:: 2.6
342
343q(uit)
344 Quit from the debugger. The program being executed is aborted.
345
346
347.. _debugger-hooks:
348
349How It Works
350============
351
352Some changes were made to the interpreter:
353
354* ``sys.settrace(func)`` sets the global trace function
355
356* there can also a local trace function (see later)
357
358Trace functions have three arguments: *frame*, *event*, and *arg*. *frame* is
359the current stack frame. *event* is a string: ``'call'``, ``'line'``,
360``'return'``, ``'exception'``, ``'c_call'``, ``'c_return'``, or
361``'c_exception'``. *arg* depends on the event type.
362
363The global trace function is invoked (with *event* set to ``'call'``) whenever a
364new local scope is entered; it should return a reference to the local trace
365function to be used that scope, or ``None`` if the scope shouldn't be traced.
366
367The local trace function should return a reference to itself (or to another
368function for further tracing in that scope), or ``None`` to turn off tracing in
369that scope.
370
371Instance methods are accepted (and very useful!) as trace functions.
372
373The events have the following meaning:
374
375``'call'``
376 A function is called (or some other code block entered). The global trace
377 function is called; *arg* is ``None``; the return value specifies the local
378 trace function.
379
380``'line'``
381 The interpreter is about to execute a new line of code (sometimes multiple line
382 events on one line exist). The local trace function is called; *arg* is
383 ``None``; the return value specifies the new local trace function.
384
385``'return'``
386 A function (or other code block) is about to return. The local trace function
387 is called; *arg* is the value that will be returned. The trace function's
388 return value is ignored.
389
390``'exception'``
391 An exception has occurred. The local trace function is called; *arg* is a
392 triple ``(exception, value, traceback)``; the return value specifies the new
393 local trace function.
394
395``'c_call'``
396 A C function is about to be called. This may be an extension function or a
397 builtin. *arg* is the C function object.
398
399``'c_return'``
400 A C function has returned. *arg* is ``None``.
401
402``'c_exception'``
403 A C function has thrown an exception. *arg* is ``None``.
404
405Note that as an exception is propagated down the chain of callers, an
406``'exception'`` event is generated at each level.
407
408For more information on code and frame objects, refer to :ref:`types`.
409