Home > Software design >  Python argparse - Detect if list argument is passed without anything afterwards
Python argparse - Detect if list argument is passed without anything afterwards

Time:09-17

Let's say the user types:

./args.py --create --mem 5

and my parser looks like this:

parser.add_argument('--create', nargs='*', default=None)

Normally --create takes a list with nargs='*', however in this case the user passed nothing.

What I would like to happen is that --create is set to the default value when invoked, instead I get []

Question: Is there anyway to detect if --create shows up in the command line arguments without anything after it?

CodePudding user response:

Here is a simple code snippet:

import argparse


parser = argparse.ArgumentParser()
parser.add_argument('--create', nargs='*', default=None)
options = parser.parse_args()
print(options)

Here are a few interactions:

$ ./args.py 
Namespace(create=None)

$ ./args.py --create
Namespace(create=[])

$ ./args.py --create one
Namespace(create=['one'])

$ ./args.py --create one two
Namespace(create=['one', 'two'])

As you can see, if the user does not add the --create flag, it is None. If the user use --create flag with nothing, you get an empty list.

  • Related