[Chicago] __name__ == "__main__"

skip at pobox.com skip at pobox.com
Fri Oct 26 23:25:59 CEST 2007

    Chris> I'm guilty of not doing this often enough.  Sometimes I treat
    Chris> Python like a *gasp* scripting language.

Me as well.  When I have my thinking cap on I start with this:

    #!/usr/bin/env python

    Python Script Template

    usage %(prog)s [ -h ] ...

    -h - print this documentation and exit.

    import sys
    import getopt

    prog = sys.argv[0]

    def usage(msg=None):
        if msg is not None:
            print >> sys.stderr, msg
        print >> sys.stderr, __doc__.strip() % globals()

    def main(args):
            opts, args = getopt.getopt(args, "h", ["help"])
        except getopt.GetoptError, msg:
            return 1

        for opt, arg in opts:
            if opt in ("-h", "--help"):
                return 0

        return 0

    if __name__ == "__main__":

Replacing getopt with optparse if I get *really* formal.  (I know optparse
is "better" for some definition of that word, but my fingers know how to
type getopt-using code with little or no involvement on the part of my


More information about the Chicago mailing list