Guest User

Untitled

a guest
Mar 20th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. import argparse
  2.  
  3. # this file shows how to use argparse
  4.  
  5. # step 1,默认构造器
  6. parser = argparse.ArgumentParser()
  7.  
  8. # step 2, 必须输入的参数,只能在1,2,4中选一个
  9. parser.add_argument("level", type=int, choices=[1, 2, 4], help="which level to print.")
  10.  
  11. # step 3, 可选参数,默认值为4
  12. parser.add_argument("-l" , "--len", type=float, default=4, help="length of something.")
  13.  
  14. # step 4, 转换成变量
  15. args = parser.parse_args()
  16. print args
  17.  
  18. # 若运行 python argparse.py -h 可查看帮助
  19. '''
  20. usage: argparse.py [-h] [-l LEN] {1,2,4}
  21.  
  22. positional arguments:
  23. {1,2,4} which level to print.
  24.  
  25. optional arguments:
  26. -h, --help show this help message and exit
  27. -l LEN, --len LEN length of something.
  28. '''
  29.  
  30. # step 5, 添加二选一的选项 --verbose | --no-verbose
  31. feature = parse.add_mutually_exclusive_group(required=False) # 互斥组
  32. feature.add_argument("--verbose", dest='verbose', action='store_true', help="verbose")
  33. feature.add_argument("--no-verbose", dest='verbose', action='store_false', help='no verbose')
  34. parser.set_defaults=(feature=True) # 默认值为True,布尔值会存在args.verbose里
  35.  
  36. # 这样子的话,输出就会多一个像这样的选项啦! [-h] [--verbose | --no-verbose]
Add Comment
Please, Sign In to add comment