Parse command line options

Klaus Alexander Seistrup klaus at seistrup.dk
Mon Apr 18 04:29:27 EDT 2005


Hue wrote:

>     try:
>
>         opts,args = getopt.getopt(sys.argv[1:], 'n:t:h:i:o:',
> ["Number=","time=","help=","image_file=","Output Filename="])
>
>     except getopt.GetoptError:
>         print 'Unrecognized argument or option'
>         usage()
>         sys.exit(0)

Proceed with e.g.:

#v+

    for (opt, arg) in opts:
        if opt in ('-n', '--No'):
            do_no()
        elif opt in ('-t', '--Time'):
            do_time()
        # [...]
        else:
            barf(opt, arg)
        # end if
    # end for

#v-

But be consistent when using long options: use all lowercase, use either
dashes or underscores (not both), don't use whitespace.

I usually do something like:

#v+

    Options = {
        'i:': 'input=',
        'o:': 'output=',
        'c' : 'copyright',
        'h' : 'help',
        'v' : 'version',
    }
    shortOpts = ''.join(Options.keys())
    longOpts  = Options.values()

    # [...]

    try:
        (opts, args) = getopt.getopt(argv[1:], shortOpts, longOpts)
    except getopt.error, msg:
        die(msg)
    # end try

    # [...]

    for (opt, arg) in opts:
        # Handle all options
	    :
    # end for

#v-

Additional, non-option, arguments will be in the "args" variable.

Cheers,

-- 
Klaus Alexander Seistrup
Magnetic Ink, Copenhagen, Denmark
http://magnetic-ink.dk/



More information about the Python-list mailing list