Python Template


Guido himself writes a short tutorial on good Python main functions at artima developer. Since he doesn’t include a final template incorporating all of his suggestions, here it is.

#!/usr/bin/python
"""Module docstring.

This serves as a long usage message.
"""
import sys
import getopt

def main(argv=None):
    if argv is None:
        argv = sys.argv

    # parse command line options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
        except getopt.error, msg:
            raise Usage(msg)
        # process options
        for o, a in opts:
            if o in ("-h", "--help"):
                print __doc__
                return 0
        # process arguments
        for arg in args:
            process(arg) # process() is defined elsewhere
    except Usage, err:
        print >>sys.stderr, err.msg
        print >>sys.stderr, "for help use --help"
        return 2

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

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

No Comments

No comments yet.

Comments RSS TrackBack Identifier URI

Leave a comment


powered by WordPress     themed by Mukkamu     presented by ideaharbor.org     everything else by steve hulet