Simpler way to put PDB breakpoints in Python code? Simpler way to put PDB breakpoints in Python code? python python

Simpler way to put PDB breakpoints in Python code?


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.


You can use:

from pdb import set_trace as bpcodecodebp()codecode


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"    endifendfunctionnmap <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.