Python starter script
From Noah.org
My starter template for a Python CLI script
This is my quintessential Python starter template for command-line scripts. This is a elaborate hello world that I use whenever I start a new script.
What inspired this is that whenever I wrote a shell script I always found myself going back to add readline support; then getopt arg parsing; then exception handling; then help documentation, etc... I'd always end up with this hello world script at the core. So what I did was pull this out and make it pretty.
To make this even more useful I have Vim use this as a template for new Python files. I added the following lines to my .vimrc:
augroup BufNewFileFromTemplate au! autocmd BufNewFile * silent! 0r $HOME/.vim/templates/%:e.tpl autocmd BufNewFile * normal! G"_dd1G autocmd BufNewFile * silent! match Todo /TODO/ augroup BufNewFileFromTemplate
Then I put this script in a file named:
~/.vim/templates/py.tpl
Now whenever I start a new Python script Vim will automatically copy this template into my buffer.
Click to download: py.tpl
#!/usr/bin/env python # vim:ts=4:sw=4:expandtab:ft=python:fileencoding=utf-8 """ SYNOPSIS TODO helloworld [-h] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR TODO: Name <name@example.org> LICENSE This script is in the public domain, free from copyrights or restrictions. VERSION $Id: py.tpl 241 2008-04-22 20:00:40Z root $ """ import sys, os, traceback, optparse import time import re #from pexpect import run, spawn # Uncomment the following section if you want readline history support. #import readline, atexit #histfile = os.path.join(os.environ['HOME'], '.TODO_history') #try: # readline.read_history_file(histfile) #except IOError: # pass #atexit.register(readline.write_history_file, histfile) def main (): global options, args # TODO: Do something more interesting here... print 'Hello world!' if __name__ == '__main__': try: start_time = time.time() parser = optparse.OptionParser(formatter=optparse.TitledHelpFormatter(), usage=globals()['__doc__'], version='$Id: py.tpl 241 2008-04-22 20:00:40Z root $') parser.add_option ('-v', '--verbose', action='store_true', default=False, help='verbose output') (options, args) = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if options.verbose: print time.asctime() main() if options.verbose: print time.asctime() if options.verbose: print 'TOTAL TIME IN MINUTES:', if options.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1)