Argparse argument with default and optional value
-
nargs
-
const
-
Instead of
default
we use theconst
parameter here -
We tell argparse that the value of the parameter is optional by
nargs='?'
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--level', help='Some level', type=int, const=10, nargs='?')
args = parser.parse_args()
print(args.level)
$ python argument_with_optional_value.py
None
$ python argument_with_optional_value.py --level
10
$ python argument_with_optional_value.py --level 20
20