问题
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