Debugging Python in VIM

Debugging Python in VIM

Following my thoughts yesterday, here are some VIM python scripts to add python breakpoint and debugging features to VIM. With this set up the F7 key will set a breakpoint on a line of code, Shift-F7 will remove all breakpoints and Shift-F12 will execute a script in the python debugger. This only runs on windows as far as I know, because it uses the 'start' command to launch the debugger in a seperate process without VIM waiting for it to finish. This allows you to look through the source code (and fix it) while the debugging is still in progress.

This goes in a python block in _vimrc:

def SetBreakpoint():
import re

nLine = int( vim.eval( 'line(".")'))

strLine = vim.current.line
strWhite = re.search( '^(\s*)', strLine).group(1)

vim.current.buffer.append(
"%(space)spdb.set_trace() %(mark)s Breakpoint %(mark)s" %
{'space':strWhite, 'mark': '#' * 30}, nLine - 1)

for strLine in vim.current.buffer:
if strLine == "import pdb":
break
else:
vim.current.buffer.append( 'import pdb', 0)
vim.command( 'normal j1')

vim.command( 'map <f7> :py SetBreakpoint()<cr>')

def RemoveBreakpoints():
import re

nCurrentLine = int( vim.eval( 'line(".")'))

nLines = []
nLine = 1
for strLine in vim.current.buffer:
if strLine == 'import pdb' or strLine.lstrip()[:15] == 'pdb.set_trace()':
nLines.append( nLine)
nLine += 1

nLines.reverse()

for nLine in nLines:
vim.command( 'normal %dG' % nLine)
vim.command( 'normal dd')
if nLine < nCurrentLine:
nCurrentLine -= 1

vim.command( 'normal %dG' % nCurrentLine)

vim.command( 'map <s-f7> :py RemoveBreakpoints()<cr>')

def RunDebugger():
vim.command( 'wall')
strFile = vim.eval( "g:mainfile")
vim.command( "!start python -m pdb %s" % strFile)

vim.command( 'map <s-f12> :py RunDebugger()<cr>')

This relies on using the runscript plugin, and modifying the function 'SetMainScript' as follows:

function s:SetMainScript()
let s:mainfile = bufname('%')
let g:mainfile = bufname('%')
echo s:mainfile . ' set as the starting program.'
endfunction

This allows F11 to be used to select which file is executed to start debugging. F12 can still be used to launch the script outside of the debugger.

Now I don't need WingIDE or a pc upgrade.

Related Topics: windows php python vim wingide

Peter's blog | add new comment

你可能感兴趣的:(#Python)