vim, compile python

Oleg Broytmann phd at phd.pp.ru
Thu Jun 6 15:08:47 CEST 2002


Hello!

For those who use vim editor.

   Put this into your .vimrc:

" Set options for python files
autocmd FileType python set autoindent smartindent
   \ cinwords=class,def,elif,else,except,finally,for,if,try,while
   \ makeprg=compyle4vim.py
   \ errorformat=%E\ \ File\ \"%f\"\\,\ line\ %l\\,\ column\ %c,%C%m |
   \ execute "autocmd BufWritePost " . expand("%") . " call DoPython()"

" Compile (clearing *.cgi[co] files after compilation)
" and if it is script, make it executable
function DoPython()
   !compyle %
   if expand("%:e") != "py"
      !rm -f %[co]
   endif
   if getline(1) =~ "^#!"
      !chmod +x %
   endif
endfunction

   The compyle and compyle4vim.py programs are attached.

   Now comments. The first line (autocmd) does not need any explanation. In the
second line there are listed keywords after which <Enter> not only opens
new line but also does indent.
   The third and fourth lines give the name of makeprg (the program for the
:make command) and the format of its error output. If you have a python
program with syntax errors open the program in vim and execute the command
:make %
   vim will run makeprg (compyle4vim.py) and parse its output, then put
cursor to the line and column with the error and report the error on the
status line.
   The fifth line teaches vim to call DoPython function upon saving the
file. The function runs compyle (shell script that uses py_compile.py), and
if the file is a script (starts with #!) makes it executable.

   The compyle script is useful for all users, not only for the users of
vim, and probably those who use Emacs could use compyle4vim.py :)

Oleg.
-- 
     Oleg Broytmann            http://phd.pp.ru/            phd at phd.pp.ru
           Programmers don't die, they just GOSUB without RETURN.
-------------- next part --------------
#! /usr/local/bin/python -O


import sys


filename = sys.argv[1]
infile = open(filename, 'r')
codestring = infile.read()
infile.close()

try:
   compile(codestring, filename, "exec")
except SyntaxError, detail:
   pass
else:
   sys.exit()

msg, (_fname, lineno, offset, line) = detail

sys.stderr.write("""  File "%s", line %d, column %d
SyntaxError: %s
""" % (filename, lineno, offset, msg))
-------------- next part --------------
#! /bin/sh

if [ "$1" = "-1" ]; then
   only_one=1
   shift
fi

if [ -z "$1" ]; then
   echo "Usage: compyle [-1] file.py..."
   exit 1
fi

TEMPLATE="from py_compile import compile; compile('"

if [ "$only_one" = "1" ]; then
   pgm=$TEMPLATE$1"')"
   python -c "$pgm" || exit 1
else
   for file in "$@"; do
      pgm=$TEMPLATE$file"')"
      python -c   "$pgm" || exit 1
      python -OOc "$pgm" || exit 1
   done
fi

#pgm="$HOME/lib/python/com.py"
#python $pgm "$@" && python -O $pgm "$@"


More information about the Python-list mailing list