Elkan
Elkan

Reputation: 616

python argparse different value if arg is provided in command line or absent

I want to use python's argparse to config the parameters input from command line. The behaviours for parsing the arguments can be:

  1. None if the name is absent from command line.
  2. Defaults to a value if the name is provided but left empty.
  3. 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?

Upvotes: 0

Views: 317

Answers (1)

Elkan
Elkan

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

Related Questions