Argparse - differentiate between no options, option invoked, and option invoked with argument?

送分小仙女□ 提交于 2019-12-02 03:41:23

问题


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.


回答1:


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')


来源:https://stackoverflow.com/questions/40644096/argparse-differentiate-between-no-options-option-invoked-and-option-invoked

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!