ArgumentParser:具有可选值的可选参数 [英] ArgumentParser: Optional argument with optional value

查看:433
本文介绍了ArgumentParser:具有可选值的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个带有可选参数值的可选参数,是否有一种方法可以验证是否在未给出值的情况下设置了参数?

If I have an optional argument with optional argument value, is there a way to validate if the argument is set when the value is not given?

例如:

parser = argparse.ArgumentParser()
parser.add_argument('--abc', nargs='?')
args = parser.parse_args()

可以正确地给我:

optional arguments:
    --abc [ABC]

如何区分下面的1和2?

How do I distinguish between 1 and 2 below?

  1. ''=> args.abc为None
  2. '-abc'=> args.abc仍然为无
  3. '-abc something'=> args.abc是某物

...

更新:

找到了解决此问题的技巧:可以使用"nargs ='*'"代替"nargs ='?'".这样,#1将返回None,而#2将返回一个空列表.缺点是这也会使参数的多个值也被接受;因此您需要在适当时添加一张支票.

Found a trick to solve this problem: you can use "nargs='*'" instead of "nargs='?'". This way #1 would return None, and #2 would return an empty list. The downside is this will allow multiple values for the arguments to be accepted too; so you'd need to add a check for it if appropriate.

或者,您也可以为参数设置默认值;请参阅chepner和Anand S Kumar的回答.

Alternatively you can also set a default value for the argument; see answer from chepner and Anand S Kumar.

推荐答案

为该选项使用其他默认值.比较

Use a different default value for the option. Compare

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--abc', nargs='?', default="default")
>>> parser.parse_args()
Namespace(abc='default')
>>> parser.parse_args(['--abc'])
Namespace(abc=None)
>>> parser.parse_args(['--abc', 'value'])
Namespace(abc='value')

我不确定在没有参数的情况下使用--abc时会如何提供一个不同的值,缺少使用自定义操作而不是nargs参数的情况.

I'm not sure how you would provide a different value for when --abc is used without an argument, short of using a custom action instead of the nargs argument.

这篇关于ArgumentParser:具有可选值的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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