简体   繁体   English

反正有没有说服python的getopt来处理选项的可选参数?

[英]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. 根据python的getopt文档(我认为),选项字段应该表现为getopt()函数。 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. getopt不支持可选参数。 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. 你会发现argparse模块更灵活。

Unfortunately, there is no way. 不幸的是,没有办法。 From the optparse docs : 来自optparse文档

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"? 这有点争议,因为它使解析变得模糊:如果“-a”采用可选参数而“-b”完全是另一种选择,我们如何解释“-ab”? Because of this ambiguity, optparse does not support this feature. 由于这种模糊性,optparse不支持此功能。

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. 编辑: oops,对于optparse模块而不是getopt模块,但是为什么两个模块都没有“可选选项参数”的原因对两者都是相同的。

You can do an optional parameter with getopt like this: 您可以像这样使用getopt执行可选参数:

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. 如果您使用的是2.3或更高版本,则可能需要尝试使用optparse模块,因为它“更方便,更灵活,功能更强大......”,以及更新版本。 Alas, as Pynt answered, it doesn't seem possible to get exactly what you want. 唉,正如Pynt回答的那样,似乎不可能得到你想要的东西。

python's getopt should really support optional args, like GNU getopt by requiring '=' be used when specifying a parameter. python的getopt应该真正支持可选的args,比如GNU getopt,需要在指定参数时使用'='。 Now you can simulate it quite easily though, with this constraint by implicitly changing --option to --option= 现在你可以很容易地模拟它,通过隐式改变--option到--option =这个约束

IE you can specify that --option requires an argument, and then adjust --option to --option= as follows: IE你可以指定--option需要一个参数,然后调整--option到--option =如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM