Wednesday, December 26, 2018

python - Parsing boolean values with argparse



I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example:



my_program --my_boolean_flag False


However, the following test code does not do what I would like:



import argparse

parser = argparse.ArgumentParser(description="My parser")
parser.add_argument("--my_bool", type=bool)
cmd_line = ["--my_bool", "False"]
parsed_args = parser.parse(cmd_line)


Sadly, parsed_args.my_bool evaluates to True. This is the case even when I change cmd_line to be ["--my_bool", ""], which is surprising, since bool("") evalutates to False.



How can I get argparse to parse "False", "F", and their lower-case variants to be False?


Answer




Yet another solution using the previous suggestions, but with the "correct" parse error from argparse:



def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:

raise argparse.ArgumentTypeError('Boolean value expected.')


This is very useful to make switches with default values; for instance



parser.add_argument("--nice", type=str2bool, nargs='?',
const=True, default=False,
help="Activate nice mode.")



allows me to use:



script --nice
script --nice


and still use a default value (specific to the user settings). One (indirectly related) downside with that approach is that the 'nargs' might catch a positional argument -- see this related question and this argparse bug report.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...