I am trying to use the argparse module to make my Python program accept flexible command-line arguments. I want to pass a simple boolean flag, and saying True
or False
to execute the appropriate branch in my code.
Consider the following.
import argparse
parser = argparse.ArgumentParser(prog='test.py',formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-boolflag', type=bool, default=True)
parser.add_argument('-intflag' , type=int, default=3)
args = parser.parse_args()
boolflag = args.boolflag
intflag = args.intflag
print ("Bool Flag is ", boolflag)
print ("Int Flag is ", intflag)
When I tried to execute it with python scrap.py -boolflag False -intflag 314
I got the result
Bool Flag is True
Int Flag is 314
Why is this?!! The intflag seems to be parsed correctly, yet the boolean flag is invariably parsed as True
even if I mention explicitly in the command-line arguments that I want it to be False
.
Where am I going wrong?
The boolean value is always assigned, so that it can be used in logical statements without checking beforehand: import argparse parser = argparse. ArgumentParser(description="Parse bool") parser. add_argument("--do-something", default=False, action="store_true", help="Flag to do something") args = parser.
parser. add_argument('indir', type=str, help='Input dir for videos') created a positional argument. For positional arguments to a Python function, the order matters. The first value passed from the command line becomes the first positional argument. The second value passed becomes the second positional argument.
Metavar: It provides a different name for optional argument in help messages.
You are trying to turn the string "False"
into a boolean:
>>> bool("False")
True
That won't work because the string "False"
is a non-empty value. All non-empty strings have a True
boolean value.
Use a store_false
action instead:
parser.add_argument('--disable-feature', dest='feature',
action='store_false')
Now when you use that switch, False
is stored, otherwise the default is True
(set by action='store_false'
).
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