argparse 模块如何在没有任何参数的情况下添加选项? [英] argparse module How to add option without any argument?

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

问题描述

我使用 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()如果 args.file:config_file = args.file如果 args.set_in_prod:模拟 = 真别的:经过

出现以下错误:

文件/usr/local/lib/python2.6/dist-packages/argparse.py",第2169行,_get_nargs_patternnargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)类型错误:不能将序列乘以str"类型的非整数

'' 而不是 0 的相同错误.

解决方案

As @Felix Kling 建议使用action='store_true':

<预><代码>>>>从 argparse 导入 ArgumentParser>>>p = ArgumentParser()>>>_ = p.add_argument('-f', '--foo', action='store_true')>>>args = p.parse_args()>>>参数文件错误的>>>args = p.parse_args(['-f'])>>>参数文件真的

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.

The args to be passed: ./script -f config_file -s or ./script -f config_file.

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.

I have tried this:

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

With the following errors:

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'

And same errror with '' instead of 0.

解决方案

As @Felix Kling suggested use 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

这篇关于argparse 模块如何在没有任何参数的情况下添加选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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