pdb — The Python Debugger
pdb — Python 调试器 ¶

Source code: Lib/pdb.py 源代码:Lib/pdb.py


The module pdb defines an interactive source code debugger for Python programs. It supports setting (conditional) breakpoints and single stepping at the source line level, inspection of stack frames, source code listing, and evaluation of arbitrary Python code in the context of any stack frame. It also supports post-mortem debugging and can be called under program control.
模块 pdb 定义了一个用于 Python 程序的交互式源代码调试器。它支持设置(条件)断点和逐行单步执行,检查堆栈帧,列出源代码,并在任何堆栈帧的上下文中评估任意 Python 代码。它还支持事后调试,并可以在程序控制下调用。

The debugger is extensible – it is actually defined as the class Pdb. This is currently undocumented but easily understood by reading the source. The extension interface uses the modules bdb and cmd.
调试器是可扩展的——它实际上被定义为类 Pdb 。这目前没有文档记录,但通过阅读源代码可以轻松理解。扩展接口使用模块 bdbcmd

See also 另请参见

Module faulthandler 模块 faulthandler

Used to dump Python tracebacks explicitly, on a fault, after a timeout, or on a user signal.
用于显式转储 Python 回溯,在故障、超时或用户信号时。

Module traceback 模块 traceback

Standard interface to extract, format and print stack traces of Python programs.
提取、格式化和打印 Python 程序堆栈跟踪的标准接口。

The typical usage to break into the debugger is to insert:
进入调试器的典型用法是插入:

import pdb; pdb.set_trace()

Or: 或:

breakpoint()

at the location you want to break into the debugger, and then run the program. You can then step through the code following this statement, and continue running without the debugger using the continue command.
在您想要进入调试器的位置,然后运行程序。您可以在此语句之后逐步执行代码,并使用 continue 命令在没有调试器的情况下继续运行。

Changed in version 3.7: The built-in breakpoint(), when called with defaults, can be used instead of import pdb; pdb.set_trace().
版本 3.7 中的更改:内置 breakpoint() ,当使用默认值调用时,可以代替 import pdb; pdb.set_trace()

def double(x):
   breakpoint()
   return x * 2
val = 3
print(f"{val} * 2 is {double(val)}")

The debugger’s prompt is (Pdb), which is the indicator that you are in debug mode:
调试器的提示符是 (Pdb) ,这是您处于调试模式的指示器:

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

Changed in version 3.3: Tab-completion via the readline module is available for commands and command arguments, e.g. the current global and local names are offered as arguments of the p command.
版本 3.3 中的更改:通过 readline 模块的 Tab 补全可用于命令和命令参数,例如当前的全局和局部名称作为 p 命令的参数提供。

You can also invoke pdb from the command line to debug other scripts. For example:
您还可以从命令行调用 pdb 来调试其他脚本。例如:

python -m pdb myscript.py

When invoked as a module, pdb will automatically enter post-mortem debugging if the program being debugged exits abnormally. After post-mortem debugging (or after normal exit of the program), pdb will restart the program. Automatic restarting preserves pdb’s state (such as breakpoints) and in most cases is more useful than quitting the debugger upon program’s exit.
当作为模块调用时,如果被调试的程序异常退出,pdb 将自动进入事后调试。在事后调试之后(或程序正常退出后),pdb 将重新启动程序。自动重启会保留 pdb 的状态(如断点),在大多数情况下比程序退出时退出调试器更有用。

Changed in version 3.2: Added the -c option to execute commands as if given in a .pdbrc file; see Debugger Commands.
版本 3.2 中的更改:添加了 -c 选项,可以像在 .pdbrc 文件中一样执行命令;参见调试器命令。

Changed in version 3.7: Added the -m option to execute modules similar to the way python -m does. As with a script, the debugger will pause execution just before the first line of the module.
版本 3.7 中的更改:添加了 -m 选项,可以像 python -m 一样执行模块。与脚本一样,调试器将在模块的第一行之前暂停执行。

Typical usage to execute a statement under control of the debugger is:
在调试器控制下执行语句的典型用法是:

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

The typical usage to inspect a crashed program is:
检查崩溃程序的典型用法是:

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

The module defines the following functions; each enters the debugger in a slightly different way:
该模块定义了以下函数;每个函数以稍微不同的方式进入调试器:

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

Execute the statement (given as a string or a code object) under debugger control. The debugger prompt appears before any code is executed; you can set breakpoints and type continue, or you can step through the statement using step or next (all these commands are explained below). The optional globals and locals arguments specify the environment in which the code is executed; by default the dictionary of the module __main__ is used. (See the explanation of the built-in exec() or eval() functions.)
在调试器控制下执行语句(作为字符串或代码对象)。在执行任何代码之前,调试器提示符会出现;你可以设置断点并输入 continue ,或者你可以使用 stepnext 逐步执行语句(所有这些命令将在下面解释)。可选的 globals 和 locals 参数指定代码执行的环境;默认情况下使用模块 __main__ 的字典。(参见内置 exec()eval() 函数的解释。)

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

Evaluate the expression (given as a string or a code object) under debugger control. When runeval() returns, it returns the value of the expression. Otherwise this function is similar to run().
在调试器控制下评估表达式(作为字符串或代码对象)。当 runeval() 返回时,它返回表达式的值。否则,此函数类似于 run()

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

Call the function (a function or method object, not a string) with the given arguments. When runcall() returns, it returns whatever the function call returned. The debugger prompt appears as soon as the function is entered.
使用给定的参数调用函数(函数或方法对象,而不是字符串)。当 runcall() 返回时,它返回函数调用的结果。调试器提示符在函数进入时立即出现。

pdb.set_trace(*, header=None)

Enter the debugger at the calling stack frame. This is useful to hard-code a breakpoint at a given point in a program, even if the code is not otherwise being debugged (e.g. when an assertion fails). If given, header is printed to the console just before debugging begins.
在调用堆栈帧中进入调试器。这对于在程序的给定点硬编码断点非常有用,即使代码没有被调试(例如,当断言失败时)。如果提供了 header,它将在调试开始前打印到控制台。

Changed in version 3.7: The keyword-only argument header.
版本 3.7 中的更改:仅限关键字参数 header。

pdb.post_mortem(traceback=None)

Enter post-mortem debugging of the given traceback object. If no traceback is given, it uses the one of the exception that is currently being handled (an exception must be being handled if the default is to be used).
进入给定回溯对象的事后调试。如果没有给定回溯,它将使用当前正在处理的异常的回溯(如果要使用默认值,必须正在处理一个异常)。

pdb.pm()

Enter post-mortem debugging of the traceback found in sys.last_traceback.
进入 sys.last_traceback 中找到的回溯的事后调试。

The run* functions and set_trace() are aliases for instantiating the Pdb class and calling the method of the same name. If you want to access further features, you have to do this yourself:
run* 函数和 set_trace() 是实例化 Pdb 类并调用同名方法的别名。如果你想访问更多功能,你需要自己完成:

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

Pdb is the debugger class.
Pdb 是调试器类。

The completekey, stdin and stdout arguments are passed to the underlying cmd.Cmd class; see the description there.
completekey、stdin 和 stdout 参数传递给底层的 cmd.Cmd 类;请参阅那里的描述。

The skip argument, if given, must be an iterable of glob-style module name patterns. The debugger will not step into frames that originate in a module that matches one of these patterns. [1]
如果提供,skip 参数必须是一个 glob 样式的模块名称模式的可迭代对象。调试器不会进入源自匹配这些模式之一的模块的帧。 [1]

By default, Pdb sets a handler for the SIGINT signal (which is sent when the user presses Ctrl-C on the console) when you give a continue command. This allows you to break into the debugger again by pressing Ctrl-C. If you want Pdb not to touch the SIGINT handler, set nosigint to true.
默认情况下,当你给出 continue 命令时,Pdb 会为 SIGINT 信号(当用户在控制台上按下 Ctrl-C 时发送)设置一个处理程序。这允许你通过按 Ctrl-C 再次进入调试器。如果你不希望 Pdb 处理 SIGINT 处理程序,请将 nosigint 设置为 true。

The readrc argument defaults to true and controls whether Pdb will load .pdbrc files from the filesystem.
readrc 参数默认为 true,控制 Pdb 是否从文件系统加载 .pdbrc 文件。

Example call to enable tracing with skip:
启用带有 skip 的跟踪的示例调用:

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

Raises an auditing event pdb.Pdb with no arguments.
引发一个没有参数的审计事件 pdb.Pdb

Changed in version 3.1: Added the skip parameter.
版本 3.1 中的更改:添加了 skip 参数。

Changed in version 3.2: Added the nosigint parameter. Previously, a SIGINT handler was never set by Pdb.
版本 3.2 中的更改:添加了 nosigint 参数。以前,Pdb 从未设置过 SIGINT 处理程序。

Changed in version 3.6: The readrc argument.
版本 3.6 中的更改:readrc 参数。

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

See the documentation for the functions explained above.
请参阅上面解释的函数的文档。

Debugger Commands 调试器命令 ¶

The commands recognized by the debugger are listed below. Most commands can be abbreviated to one or two letters as indicated; e.g. h(elp) means that either h or help can be used to enter the help command (but not he or hel, nor H or Help or HELP). Arguments to commands must be separated by whitespace (spaces or tabs). Optional arguments are enclosed in square brackets ([]) in the command syntax; the square brackets must not be typed. Alternatives in the command syntax are separated by a vertical bar (|).
调试器识别的命令如下所示。大多数命令可以缩写为一两个字母,如所示;例如 h(elp) 表示可以使用 hhelp 输入帮助命令(但不能使用 hehel ,也不能使用 HHelpHELP )。命令的参数必须用空格(空格或制表符)分隔。命令语法中的可选参数用方括号( [] )括起来;方括号不应输入。命令语法中的替代项用竖线( | )分隔。

Entering a blank line repeats the last command entered. Exception: if the last command was a list command, the next 11 lines are listed.
输入空行会重复上次输入的命令。例外情况:如果上一个命令是 list 命令,则列出接下来的 11 行。

Commands that the debugger doesn’t recognize are assumed to be Python statements and are executed in the context of the program being debugged. Python statements can also be prefixed with an exclamation point (!). This is a powerful way to inspect the program being debugged; it is even possible to change a variable or call a function. When an exception occurs in such a statement, the exception name is printed but the debugger’s state is not changed.
调试器无法识别的命令被视为 Python 语句,并在被调试程序的上下文中执行。Python 语句也可以用感叹号( ! )前缀。这是一种检查被调试程序的强大方法;甚至可以更改变量或调用函数。当此类语句中发生异常时,会打印异常名称,但调试器的状态不会改变。

The debugger supports aliases. Aliases can have parameters which allows one a certain level of adaptability to the context under examination.
调试器支持别名。别名可以有参数,这允许在检查的上下文中具有一定程度的适应性。

Multiple commands may be entered on a single line, separated by ;;. (A single ; is not used as it is the separator for multiple commands in a line that is passed to the Python parser.) No intelligence is applied to separating the commands; the input is split at the first ;; pair, even if it is in the middle of a quoted string. A workaround for strings with double semicolons is to use implicit string concatenation ';'';' or ";"";".
可以在一行中输入多个命令,用 ;; 分隔。(单个 ; 不使用,因为它是传递给 Python 解析器的行中多个命令的分隔符。)分隔命令时不应用智能;输入在第一个 ;; 对处拆分,即使它在引号字符串的中间。字符串中带有双分号的解决方法是使用隐式字符串连接 ';'';'";"";"

To set a temporary global variable, use a convenience variable. A convenience variable is a variable whose name starts with $. For example, $foo = 1 sets a global variable $foo which you can use in the debugger session. The convenience variables are cleared when the program resumes execution so it’s less likely to interfere with your program compared to using normal variables like foo = 1.
要设置一个临时的全局变量,请使用便捷变量。便捷变量是指名称以 $ 开头的变量。例如, $foo = 1 设置了一个全局变量 $foo ,你可以在调试会话中使用。便捷变量在程序恢复执行时会被清除,因此相比使用普通变量如 foo = 1 ,它们更不容易干扰你的程序。

There are three preset convenience variables:
有三个预设的便捷变量:

  • $_frame: the current frame you are debugging
    $_frame :当前正在调试的帧

  • $_retval: the return value if the frame is returning
    $_retval :如果帧正在返回,则为返回值

  • $_exception: the exception if the frame is raising an exception
    $_exception :如果帧正在引发异常,则为异常

Added in version 3.12: Added the convenience variable feature.
版本 3.12 中新增:添加了便捷变量功能。

If a file .pdbrc exists in the user’s home directory or in the current directory, it is read with 'utf-8' encoding and executed as if it had been typed at the debugger prompt, with the exception that empty lines and lines starting with # are ignored. This is particularly useful for aliases. If both files exist, the one in the home directory is read first and aliases defined there can be overridden by the local file.
如果用户的主目录或当前目录中存在文件 .pdbrc ,则使用 'utf-8' 编码读取并执行该文件,就像在调试器提示符下键入一样,唯一的例外是空行和以 # 开头的行会被忽略。这对于别名特别有用。如果两个文件都存在,则优先读取主目录中的文件,并且可以通过本地文件覆盖在那里定义的别名。

Changed in version 3.2: .pdbrc can now contain commands that continue debugging, such as continue or next. Previously, these commands had no effect.
版本 3.2 中更改: .pdbrc 现在可以包含继续调试的命令,例如 continuenext 。以前,这些命令没有效果。

Changed in version 3.11: .pdbrc is now read with 'utf-8' encoding. Previously, it was read with the system locale encoding.
版本 3.11 中更改: .pdbrc 现在使用 'utf-8' 编码读取。以前,它是使用系统区域设置编码读取的。

h(elp) [command]

Without argument, print the list of available commands. With a command as argument, print help about that command. help pdb displays the full documentation (the docstring of the pdb module). Since the command argument must be an identifier, help exec must be entered to get help on the ! command.
无参数时,打印可用命令列表。带命令作为参数时,打印该命令的帮助信息。 help pdb 显示完整文档( pdb 模块的文档字符串)。由于命令参数必须是标识符,必须输入 help exec 才能获得 ! 命令的帮助。

w(here)

Print a stack trace, with the most recent frame at the bottom. An arrow (>) indicates the current frame, which determines the context of most commands.
打印堆栈跟踪,最近的帧在底部。箭头( > )指示当前帧,它决定了大多数命令的上下文。

d(own) [count]

Move the current frame count (default one) levels down in the stack trace (to a newer frame).
在堆栈跟踪中将当前帧向下移动 count(默认为一)级(到较新的帧)。

u(p) [count]

Move the current frame count (default one) levels up in the stack trace (to an older frame).
在堆栈跟踪中将当前帧向上移动 count(默认为一)级(到较旧的帧)。

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

With a lineno argument, set a break there in the current file. With a function argument, set a break at the first executable statement within that function. The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn’t been loaded yet). The file is searched on sys.path. Note that each breakpoint is assigned a number to which all the other breakpoint commands refer.
使用 lineno 参数,在当前文件中设置一个断点。使用 function 参数,在该函数的第一个可执行语句处设置一个断点。行号可以加上文件名和冒号前缀,以指定另一个文件中的断点(可能是尚未加载的文件)。文件在 sys.path 中搜索。请注意,每个断点都会分配一个编号,所有其他断点命令都引用该编号。

If a second argument is present, it is an expression which must evaluate to true before the breakpoint is honored.
如果存在第二个参数,则它是一个表达式,必须评估为 true 才能触发断点。

Without argument, list all breaks, including for each breakpoint, the number of times that breakpoint has been hit, the current ignore count, and the associated condition if any.
无参数时,列出所有断点,包括每个断点的命中次数、当前忽略计数以及任何关联的条件。

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

Temporary breakpoint, which is removed automatically when it is first hit. The arguments are the same as for break.
临时断点,首次命中时自动移除。参数与 break 相同。

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

With a filename:lineno argument, clear all the breakpoints at this line. With a space separated list of breakpoint numbers, clear those breakpoints. Without argument, clear all breaks (but first ask confirmation).
使用 filename:lineno 参数,清除该行的所有断点。使用空格分隔的断点编号列表,清除这些断点。无参数时,清除所有断点(但首先要求确认)。

disable bpnumber [bpnumber ...]

Disable the breakpoints given as a space separated list of breakpoint numbers. Disabling a breakpoint means it cannot cause the program to stop execution, but unlike clearing a breakpoint, it remains in the list of breakpoints and can be (re-)enabled.
禁用给定的断点编号列表。禁用断点意味着它不能导致程序停止执行,但与清除断点不同,它仍然保留在断点列表中,可以重新启用。

enable bpnumber [bpnumber ...]

Enable the breakpoints specified.
启用指定的断点。

ignore bpnumber [count]

Set the ignore count for the given breakpoint number. If count is omitted, the ignore count is set to 0. A breakpoint becomes active when the ignore count is zero. When non-zero, the count is decremented each time the breakpoint is reached and the breakpoint is not disabled and any associated condition evaluates to true.
设置给定断点编号的忽略计数。如果省略 count,则忽略计数设置为 0。当忽略计数为零时,断点变为活动状态。当非零时,每次达到断点时计数递减,断点不会被禁用,并且任何关联的条件评估为 true。

condition bpnumber [condition]
conditionbpnumber [条件] ¶

Set a new condition for the breakpoint, an expression which must evaluate to true before the breakpoint is honored. If condition is absent, any existing condition is removed; i.e., the breakpoint is made unconditional.
为断点设置一个新条件,该表达式必须在断点生效前评估为真。如果没有条件,则删除任何现有条件;即,断点变为无条件。

commands [bpnumber]

Specify a list of commands for breakpoint number bpnumber. The commands themselves appear on the following lines. Type a line containing just end to terminate the commands. An example:
为断点编号 bpnumber 指定一系列命令。命令本身出现在接下来的几行中。输入仅包含 end 的一行以终止命令。示例:

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

To remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands.
要从断点中删除所有命令,请输入 commands 并立即跟随 end ;即,不给出任何命令。

With no bpnumber argument, commands refers to the last breakpoint set.
如果没有 bpnumber 参数, commands 指的是最后设置的断点。

You can use breakpoint commands to start your program up again. Simply use the continue command, or step, or any other command that resumes execution.
您可以使用断点命令重新启动程序。只需使用 continue 命令,或 step ,或任何其他恢复执行的命令。

Specifying any command resuming execution (currently continue, step, next, return, jump, quit and their abbreviations) terminates the command list (as if that command was immediately followed by end). This is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint—which could have its own command list, leading to ambiguities about which list to execute.
指定任何恢复执行的命令(目前是 continuestepnextreturnjumpquit 及其缩写)都会终止命令列表(就像该命令后立即跟随 end 一样)。这是因为每当您恢复执行时(即使是简单的 next 或 step),您可能会遇到另一个断点——该断点可能有自己的命令列表,导致关于执行哪个列表的歧义。

If you use the silent command in the command list, the usual message about stopping at a breakpoint is not printed. This may be desirable for breakpoints that are to print a specific message and then continue. If none of the other commands print anything, you see no sign that the breakpoint was reached.
如果您在命令列表中使用 silent 命令,则不会打印关于在断点处停止的常规消息。这对于要打印特定消息然后继续的断点可能是理想的。如果其他命令都没有打印任何内容,您将看不到断点已到达的任何迹象。

s(tep)

Execute the current line, stop at the first possible occasion (either in a function that is called or on the next line in the current function).
执行当前行,在第一个可能的场合停止(无论是在调用的函数中还是在当前函数的下一行)。

n(ext)

Continue execution until the next line in the current function is reached or it returns. (The difference between next and step is that step stops inside a called function, while next executes called functions at (nearly) full speed, only stopping at the next line in the current function.)
继续执行,直到到达当前函数中的下一行或返回。( nextstep 的区别在于 step 在调用的函数内停止,而 next 以(几乎)全速执行调用的函数,仅在当前函数的下一行停止。)

unt(il) [lineno]

Without argument, continue execution until the line with a number greater than the current one is reached.
无参数时,继续执行直到到达行号大于当前行号的行。

With lineno, continue execution until a line with a number greater or equal to lineno is reached. In both cases, also stop when the current frame returns.
有 lineno 参数时,继续执行直到到达行号大于或等于 lineno 的行。在这两种情况下,当当前帧返回时也会停止。

Changed in version 3.2: Allow giving an explicit line number.
版本 3.2 中更改:允许给出明确的行号。

r(eturn)

Continue execution until the current function returns.
继续执行,直到当前函数返回。

c(ont(inue))

Continue execution, only stop when a 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 execute code again, or jump forward to skip code that you don’t want to run.
设置将要执行的下一行。仅在最底层的帧中可用。这使您可以跳回并重新执行代码,或向前跳过不想运行的代码。

It should be noted that not all jumps are allowed – for instance it is not possible to jump into the middle of a for loop or out of a finally clause.
应注意,并非所有跳转都是允许的——例如,不可能跳到 for 循环的中间或跳出 finally 子句。

l(ist) [first[, last]]

List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With . as argument, list 11 lines around the current line. With one argument, list 11 lines around at that line. With two arguments, list the given range; if the second argument is less than the first, it is interpreted as a count.
列出当前文件的源代码。无参数时,列出当前行周围的 11 行或继续之前的列表。参数为 . 时,列出当前行周围的 11 行。一个参数时,列出该行周围的 11 行。两个参数时,列出给定范围;如果第二个参数小于第一个参数,则解释为计数。

The current line in the current frame is indicated by ->. If an exception is being debugged, the line where the exception was originally raised or propagated is indicated by >>, if it differs from the current line.
当前帧中的当前行由 -> 指示。如果正在调试异常,则异常最初引发或传播的行由 >> 指示(如果它与当前行不同)。

Changed in version 3.2: Added the >> marker.
版本 3.2 中更改:添加了 >> 标记。

ll | longlist

List all source code for the current function or frame. Interesting lines are marked as for list.
列出当前函数或帧的所有源代码。重要的行标记与 list 相同。

Added in version 3.2. 添加于版本 3.2。

a(rgs)

Print the arguments of the current function and their current values.
打印当前函数的参数及其当前值。

p expression

Evaluate expression in the current context and print its value.
在当前上下文中评估表达式并打印其值。

Note

print() can also be used, but is not a debugger command — this executes the Python print() function.


注意 print() 也可以使用,但这不是调试器命令——这会执行 Python print() 函数。
pp expression

Like the p command, except the value of expression is pretty-printed using the pprint module.
类似于 p 命令,但表达式的值使用 pprint 模块进行美化打印。

whatis expression

Print the type of expression.
打印表达式的类型。

source expression

Try to get source code of expression and display it.
尝试获取表达式的源代码并显示。

Added in version 3.2. 添加于版本 3.2。

display [expression]

Display the value of expression if it changed, each time execution stops in the current frame.
如果表达式的值发生变化,则在每次执行停止在当前帧时显示其值。

Without expression, list all display expressions for the current frame.
如果没有表达式,则列出当前帧的所有显示表达式。

Note

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


注意 Display 会评估表达式并与上一次评估的结果进行比较,因此当结果是可变的时,display 可能无法检测到变化。

Example: 示例:

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

Display won’t realize lst has been changed because the result of evaluation is modified in place by lst.append(1) before being compared:
Display 不会意识到 lst 已经被更改,因为在比较之前,评估结果已被 lst.append(1) 就地修改:

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

You can do 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)<module>()
-> print(lst)
display lst[:]: [1]  [old: []]
(Pdb)

Added in version 3.2. 添加于版本 3.2。

undisplay [expression]

Do not display expression anymore in the current frame. Without expression, clear all display expressions for the current frame.
不再在当前帧中显示表达式。如果没有表达式,则清除当前帧的所有显示表达式。

Added in version 3.2. 添加于版本 3.2。

interact

Start an interactive interpreter (using the code module) whose global namespace contains all the (global and local) names found in the current scope.
启动一个交互式解释器(使用 code 模块),其全局命名空间包含当前范围内的所有(全局和局部)名称。

Added in version 3.2. 添加于版本 3.2。

alias [name [command]]

Create an alias called name that executes command. The command must not be enclosed in quotes. Replaceable parameters can be indicated by %1, %2, and so on, while %* is replaced by all the parameters. If command is omitted, the current alias for name is shown. If no arguments are given, all aliases are listed.
创建一个名为 name 的别名来执行 command。命令不能用引号括起来。可替换的参数可以用 %1%2 等表示,而 %* 则替换为所有参数。如果省略 command,则显示 name 的当前别名。如果没有提供参数,则列出所有别名。

Aliases may be nested and can contain anything that can be legally typed at the pdb prompt. Note that internal pdb commands can be overridden by aliases. Such a command is then hidden until the alias is removed. Aliasing is recursively applied to the first word of the command line; all other words in the line are left alone.
别名可以嵌套,并且可以包含在 pdb 提示符下合法输入的任何内容。请注意,内部 pdb 命令可以被别名覆盖。此类命令在别名被删除之前是隐藏的。别名递归应用于命令行的第一个词;行中的其他词保持不变。

As an example, here are two useful aliases (especially when placed in the .pdbrc file):
例如,这里有两个有用的别名(特别是当它们放在 .pdbrc 文件中时):

# Print instance variables (usage "pi classInst")
alias pi for k in %1.__dict__.keys(): print(f"%1.{k} = {%1.__dict__[k]}")
# Print instance variables in self
alias ps pi self
unalias name

Delete the specified alias name.
删除指定的别名 name。

! statement

Execute the (one-line) statement in the context of the current stack frame. The exclamation point can be omitted unless the first word of the statement resembles a debugger command, e.g.:
在当前堆栈帧的上下文中执行(一行)语句。除非语句的第一个词类似于调试器命令,否则可以省略感叹号,例如:

(Pdb) ! n=42
(Pdb)

To set a global variable, you can prefix the assignment command with a global statement on the same line, e.g.:
要设置全局变量,可以在同一行的赋值命令前加上 global 语句,例如:

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

Restart the debugged Python program. If args is supplied, it is split with shlex and the result is used as the new sys.argv. History, breakpoints, actions and debugger options are preserved. restart is an alias for run.
重新启动被调试的 Python 程序。如果提供了 args,则用 shlex 分割,并将结果用作新的 sys.argv 。历史记录、断点、操作和调试器选项都将被保留。 restartrun 的别名。

q(uit)

Quit from the debugger. The program being executed is aborted.
退出调试器。正在执行的程序将被中止。

debug code

Enter a recursive debugger that steps through code (which is an arbitrary expression or statement to be executed in the current environment).
进入一个递归调试器,逐步执行代码(这是在当前环境中执行的任意表达式或语句)。

retval

Print the return value for the last return of the current function.
打印当前函数最后一次返回的返回值。

Footnotes 脚注