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