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

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

问题描述

例如:

#thing.py
import argparse

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

如何区分以下用法:

python thing.py

python thing.py --show

python thing.py --show all

本质上,如果发生以下情况,我想做不同的事情:

Essentially, I want to do different things if:

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

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

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.

推荐答案

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

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.

从文档中复制:

>>> 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天全站免登陆