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