argparse 模块如何添加不带任何参数的选项?

问题描述 投票:0回答:2

我使用

argparse
创建了一个脚本。

脚本需要一个配置文件名作为选项,用户可以指定是否需要完全执行脚本或仅模拟它。

要传递的参数:

./script -f config_file -s
./script -f config_file

-f config_file 部分没问题,但它一直要求我提供 -s 的参数,这是可选的,后面不应跟任何参数。

我试过这个:

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
也会出现同样的错误。

python argparse
2个回答
336
投票

正如 @Felix Kling 建议,要创建不需要任何值的选项,请使用

action='store_true'
'store_false'
'store_const'
。请参阅文档

>>> 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

136
投票

要创建不需要值的选项,请将其

action
[docs] 设置为
'store_const'
'store_true'
'store_false'

示例:

parser.add_argument('-s', '--simulate', action='store_true')
© www.soinside.com 2019 - 2024. All rights reserved.