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