Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import argparse
- # this file shows how to use argparse
- # step 1,默认构造器
- parser = argparse.ArgumentParser()
- # step 2, 必须输入的参数,只能在1,2,4中选一个
- parser.add_argument("level", type=int, choices=[1, 2, 4], help="which level to print.")
- # step 3, 可选参数,默认值为4
- parser.add_argument("-l" , "--len", type=float, default=4, help="length of something.")
- # step 4, 转换成变量
- args = parser.parse_args()
- print args
- # 若运行 python argparse.py -h 可查看帮助
- '''
- usage: argparse.py [-h] [-l LEN] {1,2,4}
- positional arguments:
- {1,2,4} which level to print.
- optional arguments:
- -h, --help show this help message and exit
- -l LEN, --len LEN length of something.
- '''
- # step 5, 添加二选一的选项 --verbose | --no-verbose
- feature = parse.add_mutually_exclusive_group(required=False) # 互斥组
- feature.add_argument("--verbose", dest='verbose', action='store_true', help="verbose")
- feature.add_argument("--no-verbose", dest='verbose', action='store_false', help='no verbose')
- parser.set_defaults=(feature=True) # 默认值为True,布尔值会存在args.verbose里
- # 这样子的话,输出就会多一个像这样的选项啦! [-h] [--verbose | --no-verbose]
Add Comment
Please, Sign In to add comment