Arg decoding with a template?

Skip Montanaro skip at pobox.com
Tue Jul 31 13:42:32 EDT 2001


    Dale> It looks a bit unfriendly with all the - and -- but I'll see if I
    Dale> can make some sense of it.

It's actually pretty easy to use once you learn the pattern.  I commonly use
it like so:

    alternate = ""
    binary = quiet = verbose = 0

    # split arg list up into pieces
    try:
        # colon after "a" says it needs an argument - others are boolean
        # flags
        opts, args = getopt.getopt(sys.argv[1:], "a:bqv")
    except getopt.error:
        usage()

    # process the flags
    for opt, arg in opts:
        if opt == "-a":
            alternate = arg
        elif opt == "-b:
            binary = 1
        elif opt == "-q":
            quiet = 1
        elif opt == "-v":
            verbose = 1

    # process the rest of the args
    if not args:
        infile = sys.stdin
        outfile = sys.stdout
    if len(args) == 1:
        infile = open(args[0])
        outfile = sys.stdout
    elif len(args) == 2:
        infile = open(args[0])
        outfile = open(args[1], "w")
    else:
        usage()

You can expand your getopt call to accept long args by adding a third
argument and adding the necessary tests to your for loop, but for internal
stuff I rarely do.

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list