2017年7月15日 星期六

[ Python 常見問題 ] Parsing boolean values with argparse

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: 
# my_program --my_boolean_flag False

However, the following test code does not do what I would like: 
  1. import argparse  
  2. parser = argparse.ArgumentParser(description="My parser")  
  3. parser.add_argument("--my_bool", type=bool)  
  4. cmd_line = ["--my_bool", "False"]  
  5. 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? 

How-To 
You can define a API to handle/translate the input into True/False: 
  1. def str2bool(v):  
  2.     if v.lower() in ('yes', 'true', 't', 'y', '1'):  
  3.         return True  
  4.     elif v.lower() in ('no', 'false', 'f', 'n', '0'):  
  5.         return False  
  6.     else:  
  7.         raise argparse.ArgumentTypeError('Boolean value expected.')  
The full example code: 
- test.py 
  1. import argparse  
  2.   
  3. def str2bool(v):  
  4.     if v.lower() in ('yes', 'true', 't', 'y', '1'):  
  5.         return True  
  6.     elif v.lower() in ('no', 'false', 'f', 'n', '0'):  
  7.         return False  
  8.     else:  
  9.         raise argparse.ArgumentTypeError('Boolean value expected.')  
  10.   
  11. parser = argparse.ArgumentParser(description='For testing')  
  12. parser.add_argument("--nice", "-n", type=str2bool, nargs='?',  
  13.                         const=True, default=True, required=True,  
  14.                         help="Activate nice mode.")  
  15. args = parser.parse_args()  
  16.   
  17. print("Nice=%s" % (args.nice))  
Then test it this way: 
# ./test.py 
usage: test.py [-h] --nice [NICE] 
test.py: error: argument --nice/-n is required
 
# ./test.py -n t 
Nice=True 
# ./test.py -n f 
Nice=False 
# ./test.py -n True 
Nice=True


沒有留言:

張貼留言

[ Python 文章收集 ] SQLAlchemy quick start with PostgreSQL

Source From   Here   Preface   This is a quick tutorial for getting started with   SQLAlchemy Core API .   Prerequisites   In this quick st...