问题:argparse模块如何添加不带任何参数的选项?
我使用创建了一个脚本argparse。
脚本需要使用配置文件名作为选项,用户可以指定是完全执行脚本还是仅模拟脚本。
要传递的args:./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。
回答 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
回答 1
要创建不需要任何值的选项,请设置 action [文档]的它'store_const','store_true'或'store_false'。
例:
parser.add_argument('-s', '--simulate', action='store_true')

![用Python编写单元测试:如何开始?[关闭]](https://pythondict-1252734158.file.myqcloud.com/home/www/pythondict/wp-content/uploads/2023/10/industry-4330187_1280.jpg)