Argparse - 区分无选项、调用选项和带参数调用的选项? [英] Argparse - differentiate between no options, option invoked, and option invoked with argument?

查看:32
本文介绍了Argparse - 区分无选项、调用选项和带参数调用的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举个例子:

#thing.py导入参数解析解析器 = argparse.ArgumentParser()parser.add_argument("--show", nargs='?', action="store")args = parser.parse_args()

如何区分以下用法:

python thing.pypython thing.py --showpython thing.py --显示全部

基本上,我想做不同的事情,如果:

  • 用户未指定任何选项
  • 用户自己指定--show"选项
  • 用户使用字符串/参数指定--show all".

在 add_argument 中使用 default="foo" 不起作用,因为它在测试时始终存在 - 我无法知道用户是否实际指定了选项--show".

解决方案

使用 const kwarg.如果未指定该选项,则将使用 default.如果该选项是单独提供的,则将使用 const.如果为选项提供了值,则将使用该值.

从文档中复制:

<预><代码>>>>解析器 = argparse.ArgumentParser()>>>parser.add_argument('--foo', nargs='?', const='c', default='d')>>>parser.add_argument('bar', nargs='?', default='d')>>>parser.parse_args(['XX', '--foo', 'YY'])命名空间(bar='XX', foo='YY')>>>parser.parse_args(['XX', '--foo'])命名空间(bar='XX', foo='c')>>>parser.parse_args([])命名空间(bar='d', foo='d')

As an example:

#thing.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--show", nargs='?', action="store")
args = parser.parse_args()

How do I differentiate between the following usages:

python thing.py

python thing.py --show

python thing.py --show all

Essentially, I want to do different things if:

  • The user specifies no options
  • The user specifies the "--show" option by itself
  • The user specifies "--show all" - with a string / argument.

Using default="foo" in add_argument doesn't work because it is always there when tested - I have no way to know if the user actually specified the option "--show" or not.

解决方案

Use the const kwarg. If the option is not specified, default will be used. If the option is provided on its own, const will be used. If the option is provided with a value, the value will be used.

Copying from the documentation:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='?', const='c', default='d')
>>> parser.add_argument('bar', nargs='?', default='d')
>>> parser.parse_args(['XX', '--foo', 'YY'])
Namespace(bar='XX', foo='YY')
>>> parser.parse_args(['XX', '--foo'])
Namespace(bar='XX', foo='c')
>>> parser.parse_args([])
Namespace(bar='d', foo='d')

这篇关于Argparse - 区分无选项、调用选项和带参数调用的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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