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