Silly question; best way to run a python program from Vim?

Ryan Paul segphault at
Sat Jun 12 07:46:25 CEST 2004

On Sat, 12 Jun 2004 04:35:26 +0000, Kenneth McDonald wrote:

> However, I can't quite figure out how one 'should' excute
> the Python program one is currently working on in Vim. I'm
> aware of the :python and :pyfile commands, but they seem to
> be oriented towards running scripts which are intended to
> do editing tasks, i.e. which interact with Vim. I simply want
> to do something like

I've been using python/vim for about a year now, I think. I wrote a
vim/python script that lets me easily redirect stdout to a vim buffer. I
can execute a python script, and have the output appear in a nofile
buffer. This is a bit kludgy, but its extremely useful. I have other key
bindings set up so I can use this for all sorts of things, not just python.

Here is the relevant excerpt from my vimrc - I hope you find this

""" Python Stuff
python << EOF
import vim
from vim import *
import sys,commands

def first(c,l):
  for x in l:
    if c(x): return x

txtsplit = '-'*20
CB = lambda: current.buffer
io = sys.stdout,sys.stderr
getBuf = lambda x:first(x,buffers)
pybuf = lambda x:x[0].startswith('Program Output')
prepend = lambda l,t: l[:len(l)-len(l.lstrip())] + t + l.lstrip()

def rep(t,l):
  for x in l.items():
    t = t.replace(x[0],x[1])
  return t

def getSel(l1,l2):
  return '\n'.join(current.buffer.range(int(l1),int(l2))[:])+'\n'

class vBuf:
  def __init__(s,b=None):
    s.buf = b and b or getBuf(pybuf)
    if not s.buf:
      command(':bel new')
      command(':set bt=nofile')
      s.buf = current.buffer

  def write(s,t):
    if '\n' in t: map(s.buf.append,t.split('\n'))
    else: s.buf[-1]+=t

  def clear(s):
    s.buf[:] = None
    s.buf[-1] = 'Program Output Buffer'

def redirbuf(b=None):sys.stdout = sys.stderr = vBuf(b)
def resetbuf():sys.stdout,sys.stderr = io

def PyValOut(r):
  print txtsplit

def PyExOut(r):
  print commands.getstatusoutput(r)[1]
  print txtsplit

def FileDir(x): return '/'.join(x.split('/')[:-1])
def ToFileDir(): command('lcd '+FileDir(


"""" Python Stuff
command! -range Pval py PyValOut(getSel(<f-line1>,<f-line2>))
map <leader>c :py vBuf().clear()<cr>
autocmd BufEnter *.py map <Leader>, :py PyExOut('python '+CB().name)<cr>

More information about the Python-list mailing list