How do I specify that a parsed argument should be:
False if not specifiedTrue if present (with no value)For example I would like the following to happen:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--the_arg", ...)
print(parser.parse_args(["--the_arg"]).the_arg) # should print True
print(parser.parse_args([]).the_arg) # should print False
print(parser.parse_args(["--the_arg", "my_value"]).the_arg) # should print "my_value"
The solution is to specify all of the nargs, const, and default parameters of parser.add_argument
This works:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--the_arg", nargs="?", const=True, default=False)
print(parser.parse_args(["--the_arg"]).the_arg) #prints True
print(parser.parse_args().the_arg) #prints False
print(parser.parse_args(["--the_arg", "my_value"]).the_arg) #prints "my_value"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With