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