Search code examples
pythongetoptgetopt-long

Is there anyway to persuade python's getopt to handle optional parameters to options?


According to the documentation on python's getopt (I think) the options fields should behave as the getopt() function. However I can't seem to enable optional parameters to my code:

#!/usr/bin/python
import sys,getopt

if __name__ == "__main__":
    try:
        opts, args = getopt.gnu_getopt(sys.argv[1:], "v::", ["verbose="])
    except getopt.GetoptError, err:
        print str(err)
        sys.exit(1)

    for o,a in opts:
        if o in ("-v", "--verbose"):
            if a:
                verbose=int(a)
            else:
                verbose=1
            print "verbosity is %d" % (verbose)

Results in:

$ ./testopt.py -v
option -v requires argument
$ ./testopt.py -v 1
verbosity is 1

Solution

  • getopt doesn't support optional parameters. in case of long option you could do:

    $ ./testopt.py --verbose=
    

    which will result in empty-string value.

    You could find argparse module to be more flexible. This replaces the older optparse module.