Reputation: 616
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.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?
Upvotes: 0
Views: 317
Reputation: 616
After searching stackflow, setting default to argparse.SUPPRESS
in add_argument
is of great help, as inspired by this answer.
parser = argparse.ArgumentParser()
parser.add_argument("-generate-config", metavar="-g", nargs="?", default=argparse.SUPPRESS)
So:
>>> args = parser.parse_args(["-g"]) # leave it empty/didn't provide value
>>> args
Namespace(generate_config=None)
>>> args = parser.parse_args([]) # the argument is empty
>>> args
Namespace()
>>> args = parser.parse_args(["-g", "parameters.txt"])
>>> args
Namespace(generate_config='parameters.txt')
Though not exactly as what I want, it still can be achieved by checking "generate_config" in args
and args.generate_config is None
.
Upvotes: 1