Difference between revisions of "Python starter script"

From Noah.org
Jump to navigationJump to search
Line 18: Line 18:
 
from pexpect import run, spawn
 
from pexpect import run, spawn
  
def exit_with_usage():
+
def exit_with_usage ():
 
     print globals()['__doc__']
 
     print globals()['__doc__']
 
     os._exit(1)
 
     os._exit(1)
  
def parse_args (options=None, long_options=None):
+
def parse_args (options='', long_options=[]):
 
     try:
 
     try:
 
         optlist, args = getopt.getopt(sys.argv[1:], options+'h?', long_options+['help','h','?'])
 
         optlist, args = getopt.getopt(sys.argv[1:], options+'h?', long_options+['help','h','?'])

Revision as of 08:56, 8 June 2007

My template for a Python starter script

This is what I use to start most of my simple python scripts.

#!/usr/bin/env python

"""This describes how to use the script. 
This docstring will be printed by exit_with_usage() 
if there is a problem or if the user requests help (-?, --help, etc.).

$Id$
"""

import sys, os, traceback
import re
import getopt
from pexpect import run, spawn

def exit_with_usage ():
    print globals()['__doc__']
    os._exit(1)

def parse_args (options='', long_options=[]):
    try:
        optlist, args = getopt.getopt(sys.argv[1:], options+'h?', long_options+['help','h','?'])
    except Exception, e:
        print str(e)
        exit_with_usage()
    options = dict(optlist)
    if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]:
        exit_with_usage()
    return (options, args)

def main ():
    (options, args) = parse_args('v')
    # if args<=0:
    #     exit_with_usage()
    if '-v' in options:
        verbose_flag = True
    else:
        verbose_flag = False

if __name__ == '__main__':
    try:
        main()
    except Exception, e:
        print 'ERROR, UNEXPECTED EXCEPTION'
        print str(e)
        traceback.print_exc()
        os._exit(1)