I want to use python's argparse
to config the parameters input from command line. The behaviours for parsing the arguments can be:
None
if the name is absent from command line.- Defaults to a value if the name is provided but left empty.
- To the provided value.
Example code can be:
parser = argparse.ArgumentParser()
parser.add_argument("-generate-config", metavar="-g", nargs="?")
Parsing it:
>>> parser.parse_args(["-g"]) # leave it empty/didn't provide value
Namespace(generate_config=None)
>>> parser.parse_args(["-g", "config.txt"])
Namespace(generate_config='config.txt')
>>> parser.parse_args([]) # absent in the command line
Namespace(generate_config=None)
So leave it empty or don't provide the argument in the command line, both values are None
. How can I set different behaviours/values for these two situations?