Source From Here
Question
I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example:
However, the following test code does not do what I would like:
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?
How-To
You can define a API to handle/translate the input into True/False:
The full example code:
- test.py
Then test it this way:
Question
I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example:
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)
How-To
You can define a API to handle/translate the input into True/False:
- def str2bool(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.')
- test.py
- import argparse
- def str2bool(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.')
- parser = argparse.ArgumentParser(description='For testing')
- parser.add_argument("--nice", "-n", type=str2bool, nargs='?',
- const=True, default=True, required=True,
- help="Activate nice mode.")
- args = parser.parse_args()
- print("Nice=%s" % (args.nice))
沒有留言:
張貼留言