2019年3月3日 星期日

[ Python 常見問題 ] Restricting values of command line options

Source From Here 
Question 
How do I restrict the values of the argparse options? 

In the below code sau option should only accept a number of 0 or 1 and bg should only allow an integer. How can I implement this? 
  1. import os  
  2. import sys, getopt  
  3. import argparse  
  4.   
  5. def main ():  
  6.     parser = argparse.ArgumentParser(description='Test script')  
  7.     parser.add_argument('-sau','--set',action='store',dest='set',help=' Set flag',required=True)  
  8.     parser.add_argument('-bg','--base_g',action='store',dest='base_g',help=' Base g',required=True)  
  9.     results = parser.parse_args() # collect cmd line args  
  10.     set = results.set  
  11.     base_g = results.base_g  
  12.   
  13. if __name__ == '__main__':  
  14.     main()  
How-To 
You can use the type and choices arguments of add_argument. To accept only '0' and '1', you'd do: 
  1. parser.add_argument(…, choices={"0", "1"})  
And to accept only integer numbers, you'd do: 
  1. parser.add_argument(…, type=int)  
Note that in choices, you’ll have to give the options in the type you specified as the type-argument. So to check for integers and allow only 0 and 1, you'd do: 
  1. parser.add_argument(…, type=int, choices={0, 1})  
Example: 
>>> import argparse 
>>> parser = argparse.ArgumentParser() 
>>> _ = parser.add_argument("-p", type=int, choices={0, 1}) 
>>> parser.parse_args(["-p", "0"]) 
Namespace(p=0)


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...