[Notes]python argparse模块

模块引入方式:

import argparse

description参数可以用于插入描述脚本用途的信息,可以为空

parser = argparse.ArgumentParser(description="your script description")  

 

添加--verbose标签,标签别名可以为-v,这里action的意思是当读取的参数中出现--verbose/-v的时候参数字典的verbose建对应的值为True,而help参数用于描述--verbose参数的用途或意义。

parser.add_argument('--verbose', '-v', action='store_true', help='verbose mode') 

转换参数字典

args = parser.parse_args()

为确保某些必需的参数有输入,可以在定义标签是增加require要求。例如下面的语句,其中required标签就是说--verbose参数是必需的,并且类型为int,输入别的类型会报错。

parser.add_argument('--verbose', required=True, type=int)

  

使用示例:

# description参数可以用于描述脚本的参数作用,默认为空
parser=argparse.ArgumentParser(description="111")
parser.add_argument('--aa','-t',action='store_true',help='sample of aa')
parser.add_argument('--bb', choices=['windows','linux'], default='windows') # 如果choice中的元素类型不是字符串类型,则要指定type
parser.add_argument('--cc',choices=[1,2,3,4,5],default=5,type=int,help='sample of bb') 
parser.add_argument("--dd", type=int, required=True, help="sample of cc")
args=parser.parse_args()
print(args.aa)

  

 

posted @ 2019-07-22 13:35  虚无真仙  阅读(173)  评论(0编辑  收藏  举报