开发者

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

开发者 https://www.devze.com 2022-12-08 12:00 出处:网络
Acco开发者_如何学编程rding 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:

Acco开发者_如何学编程rding 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


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.


Unfortunately, there is no way. From the optparse docs:

Typically, a given option either takes an argument or it doesn’t. Lots of people want an “optional option arguments” feature, meaning that some options will take an argument if they see it, and won’t if they don’t. This is somewhat controversial, because it makes parsing ambiguous: if "-a" takes an optional argument and "-b" is another option entirely, how do we interpret "-ab"? Because of this ambiguity, optparse does not support this feature.

EDIT: oops, that is for the optparse module not the getopt module, but the reasoning why neither module has "optional option arguments" is the same for both.


You can do an optional parameter with getopt like this:

import getopt
import sys

longopts, shortopts = getopt.getopt(sys.argv[1:], shortopts='', longopts=['env='])
argDict = dict(longopts)

if argDict.has_key('--env') and argDict['--env'] == 'prod':
    print "production"
else:
    print "sandbox"

Usage:

$ python scratch.py --env=prod
production

$ python scratch.py --env=dev
sandbox

$ python scratch.py
sandbox


If you're using version 2.3 or later, you may want to try the optparse module instead, as it is "more convenient, flexible, and powerful ...", as well as newer. Alas, as Pynt answered, it doesn't seem possible to get exactly what you want.


python's getopt should really support optional args, like GNU getopt by requiring '=' be used when specifying a parameter. Now you can simulate it quite easily though, with this constraint by implicitly changing --option to --option=

I.E. you can specify that --option requires an argument, and then adjust --option to --option= as follows:

for i, opt in enumerate(sys.argv):
    if opt == '--option':
        sys.argv[i] = '--option='
    elif opt == '--':
        break
0

精彩评论

暂无评论...
验证码 换一张
取 消