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