Parse command line options

thomasadunham at yahoo.co.uk thomasadunham at yahoo.co.uk
Mon Apr 18 15:32:35 EDT 2005


Hue,
It looks like you may have options and arguments confused. Arguments
are the pieces of information that your program needs to run. Options
are used to tune the behaviour of your program.

For example:
grep -i foo bar
Tries to match the expression "foo" in the file "bar", ignoring the
case of the letters. The grep program needs to know what expression to
look for and where to look, so "foo" and "bar" are arguments. Ignoring
the case of the letters is tuning the behaviour of the grep program -
in this case making it less sensitive. The program will run without it.


If your task is :
python  MyScriptName.py  n  t  h  i  o
Then n, t, h, i and o are arguments. You can get them from the args
array:

import sys
print ",".join(sys.argv)

would print "n, t, h, i, o"

If you are using options, you must put dashes before them, and they
must be before the arguments. So, if this was hue.py:

import sys
import string
import getopt

def usage():
    print '''haarp_make.py -- uses getopt to recognize options

Options: -n  -- No
         -t  -- Time
         -h  -- help
         -i  -- image_file
         -o  -- Output:filename'''

    sys.exit(1)

def main():

    print "SYS ARGV: ", ",".join(sys.argv)
    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)

    print "OPTS: ", ",".join([repr(o) for o in opts])
    print "ARGS: ", ",".join(args)

if __name__ == "__main__":
    main()


Then:
C:\temp>python hue.py n  t  h  i  o
SYS ARGV:  hue.py,n,t,h,i,o
OPTS:
ARGS:  n,t,h,i,o

And:
C:\temp>python hue.py  -i image.py n  t  h  o
SYS ARGV:  hue.py,-i,image.py,n,t,h,o
OPTS:  ('-i', 'image.py')
ARGS:  n,t,h,o

Hope that hepls.
Tom




More information about the Python-list mailing list