26

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?

smilingbuddha
  • 14,334
  • 33
  • 112
  • 189

1 Answers1

41

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343