argparse模块如何添加没有任何参数的选项?

我用argparse创建了一个脚本。

该脚本需要将配置文件名称作为选项,用户可以指定是完全执行脚本还是仅对其进行模拟。

要传递的参数: ./script -f config_file -s./script -f config_file

这对于-f config_file部分是可以的,但是它不断询问我是否是选项的参数,并且不应该跟随任何参数。

我试过这个:

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file')
#parser.add_argument('-s', '--simulate', nargs = '0')
args = parser.parse_args()
if args.file:
    config_file = args.file
if args.set_in_prod:
        simulate = True
else:
    pass

有以下错误:

File "/usr/local/lib/python2.6/dist-packages/argparse.py", line 2169, in _get_nargs_pattern
nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
TypeError: can't multiply sequence by non-int of type 'str'

''代替0同样的错误。


由于@Felix Kling建议使用action='store_true'

>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True

要创建不需要任何价值的选项,请将其action [docs]设置为'store_const''store_true''store_false'

例:

parser.add_argument('-s', '--simulate', action='store_true')
链接地址: http://www.djcxy.com/p/28547.html

上一篇: argparse module How to add option without any argument?

下一篇: Mutable Default Method Arguments In Python