我用了创建了一个脚本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
Run Code Online (Sandbox Code Playgroud)
出现以下错误:
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'
Run Code Online (Sandbox Code Playgroud)
与错误相同''
而不是0
.
jfs*_*jfs 208
作为@Felix克林建议使用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
Run Code Online (Sandbox Code Playgroud)
Fel*_*ing 89
要创建不需要任何值的选项,请将其action
[docs]设置为'store_const'
,'store_true'
或'store_false'
.
例:
parser.add_argument('-s', '--simulate', action='store_true')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
81956 次 |
最近记录: |