argparse模块如何添加不带任何参数的选项? [英] argparse module How to add option without any argument?

查看:705
本文介绍了argparse模块如何添加不带任何参数的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用argparse创建了一个脚本.

I have created a script using argparse.

脚本需要使用配置文件名作为选项,用户可以指定是完全执行脚本还是仅对脚本进行仿真.

The script needs to take a configuration file name as an option, and user can specify whether they need to proceed totally the script or only simulate it.

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

-f config_file部分可以,但它一直在询问-s的参数,该参数是可选的,不应跟随任何参数.

It's ok for the -f config_file part, but It keeps asking me for arguments for the -s which is optionnal and should not be followed by any.

我已经尝试过了:

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相同.

推荐答案

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆