17

I am trying to sort out how to pass the boolean value False from the command line to the argparser. My origninal code looked like:

import argparse
parser = argparse.ArgumentParser(allow_abbrev=True)
parser.add_argument('-data', default=True, type=bool, help='uses the history file')
args = parser.parse_args(sys.argv[1:])

From the command line, I typed: python myscript.py -data False

Also variations with single & double quotes around False. When I examine the contents of the args namespace, args.data is always True.

So I changed the argument definition from bool to str, with a string "True" default as shown below:

parser.add_argument('-data', default="True", type=str, help='uses the history file')

I then added some massaging of the args to get the boolean value I really wanted:

if re.search("f", args.data, re.I):
   args.data = False
else:
   args.data = True

This workaround does work. Is there a better way to do this?

John Brearley
  • 489
  • 1
  • 4
  • 10
  • `bool` converts any non-empty string to True https://stackoverflow.com/questions/715417/converting-from-a-string-to-boolean-in-python – dashiell Jun 20 '18 at 18:10
  • You can also use `store_true` see: https://stackoverflow.com/questions/32884131/framework-argparse-check-if-flag-is-set – Patrick Haugh Jun 20 '18 at 18:11

3 Answers3

14

You can use the store_false or store_true parameter to add_argument (see the argparse documentation). For example, if you want the default to be True then you could add an argument with action='store_false':

parser.add_argument('--no-data', action='store_false', help="don't use the history file")

Then args.no_data will be False if you run python command.py --no-data and True if you run python command.py without the --no-data argument.

orn688
  • 830
  • 1
  • 7
  • 10
5
def my_bool(s):
    return s != 'False'

parser.add_argument('-data',default=True,type=my_bool)
dashiell
  • 812
  • 4
  • 11
5

If an argument is meant to be a boolean, you should simply use store_true or store_false, so that the presence of the option itself would result in a True or False value, and the absence of the option would result in a False or True value, respectively.

From argparse's documentation:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('--bar', action='store_false')
>>> parser.add_argument('--baz', action='store_false')
>>> parser.parse_args('--foo --bar'.split())
Namespace(foo=True, bar=False, baz=True)
blhsing
  • 91,368
  • 6
  • 71
  • 106