Python 2.6 - Parse arguments
Question: Problem: Need to parse some specific arguments which could be in any order,
non are optional: -h -d -src -dst

Am new to Python and have looked at the alternatives such as getopt and
argparse but couldn't get a working example so went custom as below;

    
    
    argv=sys.argv[1:]
    args=[]
    for idx, arg in enumerate(argv):
        # if is arg
        if arg.startswith("-"):
            # find arg match
            for i in ("-h","-d:","-src:","-dst:"):
                # requires var
                if i == arg + ':' and idx < len(argv)-1:
                    if not argv[idx+1].startswith("-"):
                        args.append((arg,argv[idx+1]))
                        break
                # no var
                elif i == arg:
                    args.append((arg,""))
                    break
        else:
            continue
    # may contain duplicates
    print(args)
    # no dupes
    print(set(args))
    

Can anyone suggest improvements and/or better examples to achieve the problem
objective?


Answer: in python 2.6 there is a module called
[optparse](http://docs.python.org/library/optparse.html)

which does what you want.

example from the docs:

    
    
    from optparse import OptionParser
    [...]
    parser = OptionParser()
    parser.add_option("-f", "--file", dest="filename",
                      help="write report to FILE", metavar="FILE")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose", default=True,
                      help="don't print status messages to stdout")
    
    (options, args) = parser.parse_args()
    

another example:

    
    
    usage = "usage: %prog [options] arg1 arg2"
    parser = OptionParser(usage=usage)
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose", default=True,
                      help="make lots of noise [default]")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose",
                      help="be vewwy quiet (I'm hunting wabbits)")
    parser.add_option("-f", "--filename",
                      metavar="FILE", help="write output to FILE")
    parser.add_option("-m", "--mode",
                      default="intermediate",
                      help="interaction mode: novice, intermediate, "
                           "or expert [default: %default]")
    

