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?
Advertisement
Answer
Here is a simple code snippet:
JavaScript
x
8
1
import argparse
2
3
4
parser = argparse.ArgumentParser()
5
parser.add_argument('--create', nargs='*', default=None)
6
options = parser.parse_args()
7
print(options)
8
Here are a few interactions:
JavaScript
1
12
12
1
$ ./args.py
2
Namespace(create=None)
3
4
$ ./args.py --create
5
Namespace(create=[])
6
7
$ ./args.py --create one
8
Namespace(create=['one'])
9
10
$ ./args.py --create one two
11
Namespace(create=['one', 'two'])
12
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.