Daniel Stephens
Daniel Stephens

Reputation: 3259

Use Pythons argparse to make an argument being a flag or accepting a parameter

I am using argparse in Python 3. My requirement is to support the following 3 use-cases:

$ python3 foo.py --test       <== results e.g. in True
$ python3 foo.py --test=foo   <== results in foo
$ python3 foo.py              <== results in arg.test is None or False

I found store_true, and store, but can't find any configuration where I can achieve the following arg list as mentioned above. Either it wants to have a parameter, or None. Both seems not to work. Is there any way to make a argument optional?

Upvotes: 1

Views: 1028

Answers (1)

wjandrea
wjandrea

Reputation: 33179

Use nargs='?' to make the argument optional, const=True for when the flag is given with no argument, and default=False for when the flag is not given.

Here's the explanation and an example from the documentation on nargs='?':

'?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced. Some examples to illustrate this:

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

Upvotes: 2

Related Questions