Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is argparse not parsing my boolean flag correctly? [duplicate]

Tags:

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?

like image 663
smilingbuddha Avatar asked Jan 14 '17 22:01

smilingbuddha


People also ask

How do you pass a Boolean in a command line argument in Python?

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.

What is parser add_argument in Python?

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.

What is Metavar in Argparse Python?

Metavar: It provides a different name for optional argument in help messages.


1 Answers

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').

like image 73
Martijn Pieters Avatar answered Sep 19 '22 23:09

Martijn Pieters