ArgumentParser: optional argument with optional value

If I have an optional argument with an optional argument value, is there a way to check if an argument is set when no value is set?

For example:

parser = argparse.ArgumentParser()
parser.add_argument('--abc', nargs='?')
args = parser.parse_args()

      

I would correctly give me:

optional arguments:
    --abc [ABC]

      

How can I distinguish between 1 and 2 below?

  • '' => args.abc is None
  • '- abc' => args.abc is still missing
  • '- abc something' => args.abc is something.

...

Update:

Found a trick to solve this problem: you can use "nargs = '*'" instead of "nargs = '?". So # 1 will return None and # 2 will return an empty list. The disadvantage is that this will also allow multiple values ​​for the arguments; so you need to add a check for it if needed.

Alternatively, you can also set a default value for the argument; see answer from Chapner and Anand S. Kumar.

+3


source to share


3 answers


Use a different default for the parameter. Compare

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--abc', nargs='?', default="default")
>>> parser.parse_args()
Namespace(abc='default')
>>> parser.parse_args(['--abc'])
Namespace(abc=None)
>>> parser.parse_args(['--abc', 'value'])
Namespace(abc='value')

      



I'm not sure how you could provide a different value if --abc

used without an argument, instead of using a custom action instead of an argument nargs

.

+3


source


Not sure if this is the standard way, but you can set an argument default

to something, and then that value will be used in case it is --abc

not in the argument list.

Sample code -

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--abc', nargs='?', default="-1")
args = parser.parse_args()
print(args)

      



Result -

>python a.py
Namespace(abc='-1')

>python a.py --abc
Namespace(abc=None)

>python a.py --abc something
Namespace(abc='something')

      

+2


source


With, nargs='?'

you can specify both default

and const

.

In [791]: parser=argparse.ArgumentParser()    
In [792]: parser.add_argument('--abc', nargs='?', default='default', const='const')

      

If no argument is specified, it uses the default:

In [793]: parser.parse_args([])
Out[793]: Namespace(abc='default')

      

If given but without an argument string, a constant is used:

In [794]: parser.parse_args(['--abc'])
Out[794]: Namespace(abc='const')

      

Otherwise, it uses the argument string:

In [795]: parser.parse_args(['--abc','test'])
Out[795]: Namespace(abc='test')

In [796]: parser.print_help()
usage: ipython3 [-h] [--abc [ABC]]

optional arguments:
  -h, --help   show this help message and exit
  --abc [ABC]

      

+1


source







All Articles