1

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?

3
  • 1
    Don't understand results, and what is different between 1&3 ? Commented Apr 27, 2020 at 21:20
  • 2
    nargs='?' marks the argument as optional. The example given in the nargs examples[ seems to match what you're attempting to do - as soon as you clear up the confusion about example 1 & 3. Commented Apr 27, 2020 at 21:22
  • 2
    nargs='?' plus default and const values should do the trick. Commented Apr 27, 2020 at 21:55

1 Answer 1

2

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') 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.