我使用argparse
创建了一个脚本。
脚本需要使用一个配置文件名作为选项,用户可以指定是完全执行脚本,还是只模拟脚本。
要传递的参数:./script -f config_file -s
或./script -f config_file
。
对于-f config_文件部分是可以的,但是它一直在问我-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
。
要创建不需要值的选项,请将其^{} [docs] 设置为
'store_const'
、'store_true'
或'store_false'
。示例:
作为@Felix Kling suggested使用
action='store_true'
:相关问题 更多 >
编程相关推荐