Python: Difference between revisions
Line 529: | Line 529: | ||
#... | #... | ||
</pre> | </pre> | ||
If you want to use bools without store-true or store-false, you need to define an str2bool function: | |||
[https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse Stack Overflow Answer] | |||
<syntaxhighlight lang="python"> | |||
def str2bool(val): | |||
"""Converts the string value to a bool. | |||
Args: | |||
val: string representing true or false | |||
Returns: bool | |||
""" | |||
if isinstance(val, bool): | |||
return val | |||
if val.lower() in ('yes', 'true', 't', 'y', '1'): | |||
return True | |||
elif val.lower() in ('no', 'false', 'f', 'n', '0'): | |||
return False | |||
else: | |||
raise argparse.ArgumentTypeError('Boolean value expected.') | |||
#... | |||
parser.add_argument("--augment", | |||
type=str2bool, | |||
help="Augment", | |||
default=False) | |||
</syntaxhighlight> |