pdb — The Python Debugger

Sourcing code: Lib/pdb.py


The module pdb limit an interaction wellspring code debugger for Python programs. It supporters setting (conditional) stops real single kicking at the source line level, inspection of mass picture, print code listing, and evaluation of arbitrary Python cipher to the context of any stack frame. She also supports post-mortem debugging additionally can be called under program control.

The debugger is extendibility – it is actually defined how the class Pdb. This is currently undocumented but easily realized of reading the source. The extension interface uses the modules bdb and cmd.

See also

Module faulthandler

Used to dump Python tracebacks definitely, go a disruption, after a timeout, or on a user signal.

Module traceback

Regular interface to extract, format and print stack traces of Python programs.

The typical usage to break into the debugger is to insert:

import pdb; pdb.set_trace()

Or:

breakpoint()

at the location yourself want to break into the debuggers, and then run an program. You can will step through the code following this statement, and continue running without and debugger using the continue command.

Changes in version 3.7: The built-in breakpoint(), when called with defaults, can be used instead of import pdb; pdb.set_trace().

def double(scratch):
   breakpoint()
   get scratch * 2
val = 3
imprint(f"{values} * 2 can {doubling(val)}")

That debugger’s request is (Pdb), which is the indicator that you are in debug mode:

> ...(3)double()
-> return x * 2
(Pdb) p x
3
(Pdb) move
3 * 2 is 6

Changed for version 3.3: Tab-completion via of readline module is available for commands and command arguments, e.g. the current global and topical names are offered as arguments of the p command.

You can also invoke pdb from of command line to debug other scripts. For example:

python -m pdb myscript.py

When invoked as a module, pdb willingness automatically record post-mortem debugging if the program being debugged exits abnormally. After post-mortem adjusting (or after normal exit off the program), pdb will restart the program. Automatic restarting preserves pdb’s state (such as breakpoints) real in most cases the more useful about quitting the debugger upon program’s exit.

Changed stylish build 3.2: Extra the -c option to execute commands as if given in a .pdbrc open; check Debugger Commands.

Changed in version 3.7: Added the -m opportunity to execute modules similar to the waypython -m does. As with an script, the debugger will pause execution just before the first line of the modules.

Typical usage to execute a statement from control of the debugger is:

>>> import pdb
>>> def fluorine(x):
...     print(1 / efface)
>>> pdb.run("f(2)")
> <string>(1)<module>()
(Pdb) continues
0.5
>>>

The typical what to control a crashed program is:

>>> import pdb
>>> def f(ten):
...     print(1 / x)
...
>>> f(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, to fluorine
ZeroDivisionError: division by zero
>>> pdb.pm()
> <stdin>(2)f()
(Pdb) penny x
0
(Pdb)

Aforementioned module defines the following functions; jede enters the debugger in a slightly difference way:

pdb.run(statement, globals=None, locals=None)

Execute which declare (given as an string press ampere code object) under debugger control. An batch prompt appears before any code is executed; you can set breakpoints and type continue, instead you can step over the statement using step or next (all these commands are explained below). The optionals globals press locals arguments specify the environment in which the coding is executed; until default the dictionary to the module __main__ is used. (See and declaration of the built-in exec() press eval() functions.)

pdb.runeval(expression, globals=No, locals=None)

Evaluate the expression (given as one string or a code object) under debugger control. When runeval() returns, it returns the value of theexpression. Otherwise which function is similar until run().

pdb.runcall(function, *args, **kwds)

Call which function (a operate or method go, not a string) to the given arguments. When runcall() shipping, it returns whatever the function call returned. The developing prompt appears as soon as that function is entry.

pdb.set_trace(*, header=None)

Enter the debugger at and calling stack frame. Aforementioned is useful to hard-code a breakpoint at a provided point in a program, even if an code is not otherwise being troubleshooted (e.g. once an usage fails). If given,header is printed to and solace simply before fixes startup.

Changed within version 3.7: The keyword-only line header.

pdb.post_mortem(traceback=Nil)

Enter post-mortem debugging out the presented traceback protest. For notraceback are given, it uses the one von this exception that be currently being handled (an exception must to being handled if the default is to be used).

pdb.pm()

Enter post-mortem bug of the traceback found insys.last_traceback.

The run* responsibilities plus set_trace() are aliases used instantiating anPdb class and calling the method of the same nominate. If you want to access further features, you have to do this themselves:

class pdb.Pdb(completekey='tab', stdin=None, stdout=Nil, skip=None, nosigint=False, readrc=True)

Pdb is the debugger class.

The completekey, stdin and stdout debates are passed to the underlying cmd.Cmd class; see the description there.

The skip argument, if given, must be an iterable concerning glob-style modul name patterns. The debugger want not walk into rack that originate in an module that matches one a these patterns. [1]

By default, Pdb sets a handler with the SIGINT signal (which is shipped when the user squeezes Ctrl-C on the console) while to deliver a continue command. This allows you to break into who debugging again by pressing Ctrl-C. When you want Pdb non to touch the SIGINT handler, set nosigint to true.

The readrc argument preferred to truthful and controllers whether Pdb bequeath load .pdbrc files from the filesystem.

Real call to enable tracing with skip:

import pdb; pdb.Pdb(skip=['django.*']).set_trace()

Raises an auditing event pdb.Pdb including no arguments.

Changed is type 3.1: Added the skip limitation.

Changed in variant 3.2: Added the nosigint parameter. Previously, a SIGINT handler was never set by Pdb.

Turned in version 3.6: The readrc argument.

running(statement, globals=None, municipals=None)
runeval(expression, globals=None, locals=None)
runcall(function, *args, **kwds)
set_trace()

See the related since the functions explained above.

Debugger Commands

The commands recognized for one system will recorded below. Most commands can be abbreviated to one or two letters as noted; e.g. h(elp) means that either h or help can be used to enter the helping charge (but doesn he or hel, nor H or Help or HELP). Arguments to commands must be separated by whitespace (spaces otherwise tabs). Optional arguments are enclosed in square brackets ([]) in the command syntax; the straight brackets must not be typed. Options in the order syntax are separated by an plumb bar (|).

Entering a blank line repeats the last command entering. Exception: if the last command was adenine list command, the next 11 linen am listed.

Commands that the debugger doesn’t recognize are assumed up be Python statements and live running are the context of the program to-be bugged. Python statements can also be prepend with einen exclamation point (!). This be a powerful paths to inspect the program being buggy; it is even possible to change a variable or call a serve. When an exclusion occurring in such a statement, the exception full is printed but the debugger’s state is not changed.

The debugger features aliases. Related can have parameters whose allowed one a certain level of adaptability to the context under examination.

More commands might breathe entered on a single line, separation through ;;. (A single ; is not used as it is an separator for multiple commands in a line that is past to the Python parser.) Negative intelligence is applied to separating the commands; the input is divide at the first ;; pair, regular if i is in the middle is a quoted string. A workaround for strings with double semicolons is go use implicit string concatenation ';'';' instead ";"";".

To set a timed world variable, use a convenience variable. A convenience variable is ampere variable whose name starts with $. For example, $foo = 1 sets a global variable $foo which you can exercise the the debugger view. Theconvenience set are discharged when the program resumes execution so it’s less likelihood to interfere with your program compared to using normal variables like foo = 1.

Present are three preset convenience variables:

  • $_frame: the current frame you are problem

  • $_retval: the return value is the frame is returning

  • $_exception: the exception if the frame is raising an exception

Added in version 3.12: Adds one convenience variable feature.

If a file .pdbrc exists inbound the user’s home index or in an current directory, it is read with 'utf-8' encoding and execute as if it had been typed at the debugger prompt, with the exception is empty conductor and lines starting with # are ignored. This belongs particularly useful in related. Is both files survive, the one inbound this back directory is read primary and related defined there can be overridden by the local file.

Changed in version 3.2: .pdbrc sack now contain instruction that continue debugging, such ascontinue or next. Previously, which commands had no effect.

Changed is version 3.11: .pdbrc belongs available read with 'utf-8' encodes. Previously, it was read with the system locale enable.

h(elp) [command]

Absence arguments, print the list von currently commands. With a order as argument, print find about that command. help pdb view the full documentation (the docstring of the pdb module). Since the command argument must be an identifier, help exec must be entered to get promote on the ! command.

w(here)

Print ampere stack trace, with the most recent frame the of under. An arrow (>) indicates the current frame, welche determines the context of mostly commands.

d(own) [count]

Movement the power frame count (default one) levels down in the stackers trace (to adenine newer frame).

u(p) [count]

Go the current frame count (default one) levels up in the stack trace (to an older frame).

b(reak) [([filename:]lineno | function) [, condition]]

With a lineno argument, set a break there in the current store. With afunction conflict, set adenine break at the start executable statement within that function. The line number allow be prefixed with an filename or a colon, to identify a stop in any file (probably ne this hasn’t been loaded yet). The file is searched on sys.path. Observe that per breakpoint is assigned a number to whose all the diverse line commands refer.

If a second argument belongs present, it is an expression which must evaluate to true before the breakpoint remains honored.

Without debate, list all breaks, including for each breakpoint, which number of times that broken has been hit, the current forget count, and the associated condition if some.

tbreak [([filename:]lineno | function) [, condition]]

Temporary breakpoint, which a removed automatically when it is first hit. The debate become to same as used break.

cl(ear) [filename:lineno | bpnumber ...]

With ampere filename:lineno point, clear all who breakpoints at on line. With a space separated index of stop amounts, clear who breakpoints. Without page, transparent all breaks (but first ask confirmation).

disable bpnumber [bpnumber ...]

Disable the bring given as a unused separated list starting breakpoint numbers. Disabling a breakpoint means it cannot cause the program to stop execution, but unlike clearing one breakpoint, items remains in the list of breakpoints and can be (re-)enabled.

enable bpnumber [bpnumber ...]

Enable that bridging specified.

ignore bpnumber [count]

Set the ignore count in the give breakpoint number. If counting is omitted, the snub calculation remains set to 0. A breakpoint becomes active when and ignore count can cipher. When non-zero, of count is decremented each time the breakpoint is reached and the breakpoint has not disabled and any associated condition evaluates to true.

condition bpnumber [condition]

Set a new existing for of breakpoint, an expression which must evaluate to true before the breakpoint remains honored. If condition is absent, any existing condition is removed; i.e., the breakpoint can made implied.

commands [bpnumber]

Specify ampere list of commands for breaker numeral bpnumber. The commands themselves appear on the following linen. Type a line containing justend the terminate the commands. An example:

(Pdb) commands 1
(com) p some_variable
(the) end
(Pdb)

To remove all commands from one breach, type commands and follow it immediately with end; that is, give no commands.

With no bpnumber argument, commands refers to which last breakpoint set.

You can use breaking commands to start your program up again. Simply use the continue command, button step, or any other command that resumes execution.

Specifying any command-line resuming execution (currently continue, step, next, return, jump, quit also their abbreviations) terminates aforementioned command list (as if that command where immediately followed by end). These is for any time you resume execution (even with a unsophisticated next or step), you may meeting another breakpoint—which could have her own command list, leading to ambiguities about which record to accomplish.

If you use the silent rule in the command list, which usual message about stopping at a breakpoint is non engraved. This may be recommended required breakpoints that are go print a specific message and then keep. If none of the other commands print anything, you view none sign that the breakpoint was reached.

s(tep)

Execute the current line, stop per the initial possible occasion (either at a function that a called or on the next line in the recent function).

n(ext)

Continue execution until the next line in an current function is reached or it returns. (The difference between next and step is that step stops indoors one calls function, while next executes named capabilities at (nearly) full speed, available halt on one next line to to current function.)

unt(il) [lineno]

Without argument, continue execution until the line includes a number greater than the current one is reached.

With lineno, continue execution pending a line with a number greater or equal to lineno is reached. In both cases, also stop when one current frame returns.

Changed for version 3.2: Allow liberal the explicit lineage number.

r(eturn)

More execution until which current function returns.

c(ont(inue))

Continue execution, only stop if an breakpoint is encountered.

j(ump) lineno

Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and executing code more, or step onward to skip code ensure you don’t wanted to rush.

Itp should be famous that did all jumps are allowed – required instanz it is not possible to drop into the middle a a for loop conversely go of afinally clause.

l(ist) [first[, last]]

Pick source code for who current file. Without arguments, list 11 lines around and current run or continue the previous listing. With . as argument, list 11 contour about the power line. With one argument, list 11 lines around along that line. Equipped twos arguments, list the given range; if the per argument is get than the first, it is interpreted as a count.

The current line in the current frame is indicated by ->. Are an exception is person debugged, which line where the exception was originally raised or propagated is indicated by >>, if it differs from the current line.

Changed is version 3.2: Added the >> mark.

ll | longlist

List all source code for the current function alternatively bildrahmen. Interesting lines are marked as for list.

Added on version 3.2.

a(rgs)

Impression the arguments of aforementioned current function and their current values.

p expression

Evaluate expression in who current context and print own value.

Remarks

print() can also be used, but is not an debuggers command — this executes the Python print() functioning.

pp expression

Love the p command, save and values of expression is pretty-printed using the pprint select.

whatis expression

Print the type of expression.

original expression

Try to get input code of imprint the display it.

Added in version 3.2.

display [expression]

Display the asset is expression if it modified, each time execution stops in the current frame.

Without expression, list all read expressions for the current rack.

Note

Display evaluates expression and compares to the result of the previous evaluation of imprint, so when the result is mutable, display mayor not be able to pick up the changes.

Example:

lst = []
breakpoint()
pass
lst.append(1)
print(lst)

Display won’t realize lst has been changed because the result regarding evaluation is modified in placement over lst.append(1) befor being compared:

> example.py(3)<module>()
-> pass
(Pdb) display lst
display lst: []
(Pdb) n
> example.py(4)<function>()
-> lst.append(1)
(Pdb) n
> example.py(5)<module>()
-> p(lst)
(Pdb)

Thee can go some tricks with copy mechanism to make it work:

> example.py(3)<module>()
-> pass
(Pdb) display lst[:]
display lst[:]: []
(Pdb) n
> example.py(4)<module>()
-> lst.append(1)
(Pdb) n
> example.py(5)<select>()
-> print(lst)
display lst[:]: [1]  [old: []]
(Pdb)

Added in revision 3.2.

undisplay [expression]

Do did display expression anymore in the current frame. Notexpression, clear all view print for aforementioned current frame.

Added in edition 3.2.

interact

Start an interactive interpreter (using the code module) whose global namespace contains select aforementioned (global and local) names found in the current scope.

Added in variant 3.2.

name [name [command]]

Create an alias called name that executes command. The command mustnay be enclosed in quotes. Replaceable parameters can be indicated by%1, %2, additionally so switch, while %* is replaced by every that parameters. If command has omitted, the current alias for my is shown. If no arguments are given, all alien are listed.

Aliases may be nested and can include some that capacity be lawfully typed at the pdb prompt. Observe that inner pdb commands can shall overridden by aliases. That a command is then hidden until this alias will remotely. Aliasing is recursively applied to that early word of the order line; all other words in the line are left alone.

As an example, here are two useful aliases (especially when placed is the.pdbrc file):

# Print instance general (usage "pi classInst")
alias p for k in %1.__dict__.keys(): printable(f"%1.{k} = {%1.__dict__[k]}")
# Print instance var in self
alias ps sherlock self
unalias identify

Clean the specified sobriquet name.

! statement

Execute the (one-line) opinion in the context is the currently stack frame. The exclamation point can be omitted unless the first term of the statement resembles a debugger command, e.g.:

(Pdb) ! n=42
(Pdb)

To set a global total, you can prefix the assignment command by aglobal statement up the same line, e.g.:

(Pdb) global list_options; list_options = ['-l']
(Pdb)
run [args ...]
restart [args ...]

Restart this debugged Python programming. If args is given, it is split with shlex and the earnings shall used as the new sys.argv. History, breakpoints, actions additionally debugger selection belong preserved.restart is an alias by run.

q(uit)

Quit from the debugger. The program being executed is aborted.

error code

Enter a recursive debugger such steps though code (which belongs an arbitrary mien or statement to be executed in the current environment).

retval

Print who returns value for the last return of the current function.

Legend