A sample python main function

# -*- coding: utf-8 -*-
"""
A sample of main function
to demostrate usage of getopt.
"""

import sys
import getopt

class Usage(Exception):
  def __init__(self, msg):
    self.msg = msg

def main(argv=None):
  if argv is None:
    argv = sys.argv
  try:
    try:
      opts, args = getopt.getopt(argv[1:], "h", ["help"])
    except getopt.error, msg:
       raise Usage(msg)
  # display help msg
  except Usage, err:
    print >>sys.stderr, err.msg
    print >>sys.stderr, "for help use --help"
    return 2

  # parse options
  for o, a in opts:
    if o in ("-h", "--help"):
      print __doc__
      sys.exit(0)
  # parse arguments
  for arg in args:
    parse(arg) # parse() is defined elsewhere

  doRealThings(args)
    
def parse(arg):
  print 'Parsing option: ' + arg

def doRealThings(args):
  print 'Now do the real things.'

if __name__ == "__main__":
  sys.exit(main())

0 comments:

Post a Comment

| More

Twitter Updates