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