在Python代码中放置PDB断点的更简单方法?

发布于 2024-11-28 20:00:55 字数 199 浏览 1 评论 0原文

只是一个方便的问题。我对 Visual Studio 和 XCode 等 IDE 中的调试器有点着迷。我发现必须输入 import pdb; 有点笨拙。 pdb.set_trace() 设置断点(我不想在文件顶部导入 pdb,因为我可能会忘记并将其保留在其中)。

有没有一种更简单的方法可以在 Python 代码中设置断点,就像您在 IDE 中看到的那样简单且不显眼?

Just a convenience question. I've been a bit spoiled with debuggers in IDEs like Visual Studio and XCode. I find it a bit clumsy to have to type import pdb; pdb.set_trace() to set a breakpoint (I'd rather not import pdb at the top of the file as I might forget and leave it in).

Is there a simpler way of setting a breakpoint in Python code, as straightforward and unobtrusive as what you see in an IDE?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

送君千里 2024-12-05 20:00:55

您可以通过以下命令从命令行将程序运行到 pdb 中:

python -m pdb your_script.py

它将在第一行中断,然后您可以使用 break 命令在代码中的任何位置添加断点,其语法为:

b(reak) [[文件名:]lineno |函数[,条件]]

它足够灵活,可以让您在任何地方添加断点。

You can run your program into pdb from the command line by running

python -m pdb your_script.py

It will break on the 1st line, then you'll be able to add a breakpoint wherever you want in your code using the break command, its syntax is:

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

It is flexible enough to give you the ability to add a breakpoint anywhere.

烟花易冷人易散 2024-12-05 20:00:55

您可以使用:

from pdb import set_trace as bp

code
code
bp()
code
code

You can use:

from pdb import set_trace as bp

code
code
bp()
code
code
梦断已成空 2024-12-05 20:00:55

我还没有尝试过,但他们刚刚实现了 Python 3.7 中新增了一个名为 Breakpoint() 的内置函数,这意味着您现在可以使用一条语句插入断点:

breakpoint()

I haven't tried it yet but they just implemented a new built-in called breakpoint() in Python 3.7 which means you can insert a breakpoint with one statement now:

breakpoint()
温柔嚣张 2024-12-05 20:00:55

在 vim 中,我为此设置了一个宏(在我的 .vimrc 文件中):

map <silent> <leader>b oimport pdb; pdb.set_trace()<esc>
map <silent> <leader>B Oimport pdb; pdb.set_trace()<esc>

所以我只需按 \b (不在插入模式下时),它就会在当前行或 \B 之后添加一个断点(请注意大写)并在当前行之前添加一个。

这似乎工作正常。大多数其他“简单”程序员编辑器(emacs、sublimetext 等)应该有类似的简单方法来执行此操作。

编辑:
我实际上有:

au FileType python map <silent> <leader>b oimport pdb; pdb.set_trace()<esc>
au FileType python map <silent> <leader>B Oimport pdb; pdb.set_trace()<esc>

它仅针对 python 源文件打开它。您可以非常轻松地为 javascript 或您使用的任何其他语言添加类似的行。

2019 更新 (Python 3.7+)**

Python 3.7+ 现在具有内置的 breakpoint() ,可以替代之前的 import pdb; vim 中的 pdb.set_trace()。它的工作原理仍然是一样的。

2021 更新

所以这些天我做了很多 django,我还使用 ipdb 调试器,以及一些 javascript 和一些 HTML 模板,所以现在有了:

function InsertDebug()
    if &filetype == "python"
        execute "normal! oimport ipdb;ipdb.set_trace()\<esc>"
    elseif &filetype == "javascript"
        execute "normal! odebugger;\<esc>"
    elseif &filetype == "html" || &filetype == "htmldjango"
        execute "normal! o{% load debugger_tags %}{{ page\|ipdb }}\<esc>4bcw"
    else
        echoerr "Unknown filetype - cannot insert breakpoint"
    endif
endfunction
nmap <leader>b <esc>:call InsertDebug()<CR>

所以我得到了 ipdb 断点,或这些语言中的其他语言断点。然后这也可以轻松扩展到其他语言。我认为可以使用更好的自动命令来做到这一点 - 但我无法让它像这样可靠地工作。

In vim, I have a macro set up for this (in my .vimrc file):

map <silent> <leader>b oimport pdb; pdb.set_trace()<esc>
map <silent> <leader>B Oimport pdb; pdb.set_trace()<esc>

so I can just press \b (when not in Insert Mode) and it adds in a breakpoint after the current line, or \B (note the capital) and it puts one before the current line.

which seems to work alright. Most other 'simple' programmers editors (emacs, sublimetext, etc) should have similar easy ways to do this.

Edit:
I actually have:

au FileType python map <silent> <leader>b oimport pdb; pdb.set_trace()<esc>
au FileType python map <silent> <leader>B Oimport pdb; pdb.set_trace()<esc>

which turns it on only for python source files. You could very easily add similar lines for javascript or whatever other languages you use.

2019 Update (Python 3.7+)**

Python 3.7+ now has the builtin breakpoint() which can replace the previous import pdb; pdb.set_trace() in vim. It still works the same.

2021 Update

So I'm doing a lot of django these days, I'm using the ipdb debugger also, with some javascript and some HTML templating, so now have:

function InsertDebug()
    if &filetype == "python"
        execute "normal! oimport ipdb;ipdb.set_trace()\<esc>"
    elseif &filetype == "javascript"
        execute "normal! odebugger;\<esc>"
    elseif &filetype == "html" || &filetype == "htmldjango"
        execute "normal! o{% load debugger_tags %}{{ page\|ipdb }}\<esc>4bcw"
    else
        echoerr "Unknown filetype - cannot insert breakpoint"
    endif
endfunction
nmap <leader>b <esc>:call InsertDebug()<CR>

so I get either the ipdb breakpoint, or other language breakpoints in those languages. Then this is easily extendible to other languages too. I think it would be possible to use better autocommands to do this - but I couldn't get it to work as reliably as this.

谜兔 2024-12-05 20:00:55

如果您不想每次运行程序时手动设置断点(在Python 3.2+中),例如您想直接在第3行创建断点并在那里停止执行:

python -m pdb -c " b 3" -cc your_script.py

以下信息可能有所帮助:

如果文件 .pdbrc 存在于用户的主目录或当前目录中,则会读入并执行该文件,就像在调试器提示符下键入该文件一样。这对于别名特别有用。如果两个文件都存在,则首先读取主目录中的文件,并且其中定义的别名可以被本地文件覆盖。

版本 3.2 中的更改:.pdbrc 现在可以包含继续调试的命令,例如 continue 或 next。以前,这些命令没有效果。

版本 3.2 中的新增功能:pdb.py 现在接受 -c 选项,该选项执行的命令就像在 .pdbrc 文件中给出的那样,请参阅调试器命令。

If you don't want to manually set breakpoints every time running the program (in Python 3.2+), e.g. say you want to directly create a breakpoint at line 3 and stop the execution there:

python -m pdb -c "b 3" -c c your_script.py

The following information may help:

If a file .pdbrc exists in the user’s home directory or in the current directory, it is read in and executed as if it had been typed at the debugger prompt. 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.

Changed in version 3.2: .pdbrc can now contain commands that continue debugging, such as continue or next. Previously, these commands had no effect.

New in version 3.2: pdb.py now accepts a -c option that executes commands as if given in a .pdbrc file, see Debugger Commands.

浸婚纱 2024-12-05 20:00:55

Python 3.7 有一种新的内置断点设置方法。 在此处调用

breakpoint()

更多内容 https://stackoverflow.com/a/53263117/6488361

Python 3.7 has a new builtin way of setting breakpoints. Calling

breakpoint()

More here https://stackoverflow.com/a/53263117/6488361

甜柠檬 2024-12-05 20:00:55

这就是在命令行中使用 pdb 的方式,而无需在源代码中实现任何内容(文档和其他在线资源不能很好地向过去只使用过可视化调试器的程序员解释这一点):

启动 pdb通过在 shell 提示符中键入以下内容:

python -m pdb 'python_script'

此命令初始化 pdb,pdb 调试器将在 python_script 的第一行处中断并等待您的输入:

(Pdb)

这是与调试器通信的接口。现在,您可以在此处指定命令。与在可视化调试器中使用按钮或键盘快捷键不同,在这里您将使用命令来获得相同的结果。

您可以通过命令“n”(下一个)转到代码中的下一行:

(Pdb) n

执行下一个将显示行号,以及源代码中的特定代码:

> python_script(line number)method name
-> current line in the source code

您可以通过在源代码中指定行号来设置断点。

(Pdb) b 50

这里,调试器设置为在第 50 行处中断。如果没有任何其他断点,则第 50 行处的断点将是第一个断点,并且可以通过断点 ID(在本例中为 1)引用它。如果您添加更多断点,它们将按顺序获得标识符(即 2、3 等)。

设置断点后,您将继续执行程序,直到 pdb 到达断点,如下所示:

(Pdb) c

一旦到达断点,您就可以执行到下一行,使用 n 命令,如前所述。如果你想检查变量的值,你可以执行如下参数命令:

(Pdb) p variable_name

如果你不再需要断点,你可以通过clear命令传入断点的id来清除它:

(Pdb) clear 1

最后,当你完成时使用调试器,您可以退出执行,就像退出 python 命令行解释器一样。

(Pdb) exit()

我希望这能帮助任何人开始使用 pdb。以下是可与调试器一起使用的命令列表: pdb 所以问题和解答

This is how you would use pdb in the command line without implementing anything in your source code (the documentation and other online resources don't do a good job explaining this to a programmer who has only used visual debuggers in the past):

Start pdb by typing the following in a shell prompt:

python -m pdb 'python_script'

This command initializes pdb and the pdb debugger will break at the first line of your python_script and wait for an input from you:

(Pdb)

This is the interface for communicating with the debugger. Now, you can specify your commands here. Opposed to using buttons or keyboard shortcuts in visual debuggers, here you will use commands to derive the same results.

You can go to the next line in your code by command "n" (next):

(Pdb) n

Performing a next would display the line number, and the specific code in the source:

> python_script(line number)method name
-> current line in the source code

You can set a breakpoint by specifying a line number in your source code.

(Pdb) b 50

Here, the debugger is set to break at line 50. If there aren't any other breakpoints, the breakpoint at line 50 will be the first and it could be referenced by the breakpoint id which is 1 in this case. If you add more break points they will get identifiers sequentially (i.e., 2, 3 etc.)

Once a breakpoint is set, you would continue executing your program until pdb gets to the breakpoint as follows:

(Pdb) c

Once you get to a breakpoint you could go to the next line, with the n command as described before. If you want to examine the values of variables, you would execute the parameter command as follows:

(Pdb) p variable_name

If you no longer need a breakpoint, you can clear it by passing in the id of the breakpoint with the clear command:

(Pdb) clear 1

Finally, when you are done with the debugger you can exit the execution as you would exit the python command line interpreter.

(Pdb) exit()

I hope this will help anybody get started with pdb. Here is a list of commands you can use with the debugger: pdb so question and answers

以酷 2024-12-05 20:00:55

您可以使用支持Python调试的IDE,或者您可以查看优秀的Winpdb工具。它适用于任何平台,并为您的 python 脚本提供图形调试工具。

http://winpdb.org/

You could use an IDE which supports python debugging, or you can check out the excellent Winpdb tool. Which works on any platform and provides graphical debugging facilities to your python script.

http://winpdb.org/

折戟 2024-12-05 20:00:55

在运行过程中保存断点、别名和其他设置的最简单方法是在脚本所在的同一文件夹中使用 .pdbrc,然后将脚本运行为 python -m pdb.py

Enter命令就像在 pdb 中每行执行一个命令一样。
例如:

.\.pdbrc
--------
b 12
display var
c

Easiest way to keep breakpoints, aliases and other settings saved across run is by using .pdbrc in the same folder as your script and then just run your script as python -m pdb <scriptname>.py

Enter commands just as you would do in pdb one per line.
E.g.:

.\.pdbrc
--------
b 12
display var
c
蓝眼泪 2024-12-05 20:00:55

您可以使用:

  • wing ide
  • eclipse 和 pydev 插件
  • pycharms

以上所有内容都支持从 IDE 内部进行 python 调试。

You can use:

  • wing ide
  • eclipse with the pydev plugin
  • pycharms

All of the above support python debugging from inside an IDE.

ゃ人海孤独症 2024-12-05 20:00:55

(我不想在文件顶部导入 pdb,因为我可能会忘记并将其保留在其中)。

不同的是,这是“原子的”:

import pdb; pdb.set_trace()

与可能留下导入部分

__import__('pdb').set_trace()

(I'd rather not import pdb at the top of the file as I might forget and leave it in).

Unlike

import pdb; pdb.set_trace()

which could leave the import part behind, this is "atomic":

__import__('pdb').set_trace()
幻梦 2024-12-05 20:00:55

在 Atom 中,如果安装了 Python 插件,您只需输入“pdb”并按 Enter 键,代码片段就会为您输入 import 并回溯。

我现在已经习惯了,有时我只是输入它,即使我正在 vim 中编辑它并等待下拉菜单出现。

In Atom if Python plugins installed, you can just type in 'pdb' and hit enter and the snippet will type import and trace back for you.

I've used to this now that sometimes I just type it in even if I'm editing it in vim and waiting for the dropdown to appear.

月依秋水 2024-12-05 20:00:55

您可以将 Vim 与 Python-Mode 插件一起使用,或将 Emacs 与 Elpy 插件。

这些插件通过简单的击键为您提供断点(Vim 中的 \ b 和 Emacs 中的 Cc Cu b)以及来自重量级 IDE 的许多其他功能(代码折叠、重构、linting)等) - 全部在基于终端的轻量级文本编辑器中。

You could use Vim with the Python-Mode plugin or Emacs with the Elpy plugin.

These plugins give you breakpoints with easy keystrokes (\ b in Vim and C-c C-u b in Emacs) plus many other features from heavy-weight IDEs (code folding, refactoring, linting, etc.) - all within a light-weight terminal-based text editor.

伏妖词 2024-12-05 20:00:55

通过此代码片段,可以自动设置断点:

import pdb
import sys
try:
    from io import StringIO           # Python3
except:
    from StringIO import StringIO     # Python2

bp = 14    # or e.g. "submodule.py:123"

sys.stdin = StringIO('break %s\ncont\n' % bp)
pdb.set_trace()
sys.stdin = sys.__stdin__   # reset to usually stdin

print(1)     # lineno 14
print(2)

此方法适用于 Python 2 和 3。

断点也可以通过 .pdbrc 文件(本地或在家庭中)设置并动态操作。不过,cont 命令不得手动执行。
因此,由于 pdb.set_trace 需要 stdin,因此上面的代码只是以编程方式将命令“重定向”到 stdin。

将代码放在主程序中并与argparse结合,可以从命令行传递断点,并进一步停止,直到断点。

With this snippet breakpoints can be set automatically:

import pdb
import sys
try:
    from io import StringIO           # Python3
except:
    from StringIO import StringIO     # Python2

bp = 14    # or e.g. "submodule.py:123"

sys.stdin = StringIO('break %s\ncont\n' % bp)
pdb.set_trace()
sys.stdin = sys.__stdin__   # reset to usually stdin

print(1)     # lineno 14
print(2)

This approach works with Python 2 and 3.

Breakpoints could be also set via a .pdbrc file (locally or in home) and manipulated on the fly. Still, the cont command must not executed manually.
So since pdb.set_trace requires stdin, the above code just "redirects" the command to stdin in a programmatic way.

Putting the code inside the main program and combined with argparse, the breakpoints can be passed from the command line with further stop until the breakpoint.

笨死的猪 2024-12-05 20:00:55

在脚本上运行调试器的最简单方法就是

pdb your_script.py

在 Linux 命令行上运行 pdb 给出

usage: pdb.py scriptfile [arg] ...

The simplest way to run the debugger on your script is just

pdb your_script.py

Running pdb on a Linux command-line gives

usage: pdb.py scriptfile [arg] ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文