import argparse
import sys
#创建一个解析对象
parse=argparse.ArgumentParser(prog=‘我自己的程序’,usage=’%(prog)s [options] usage’,
description=‘编写自定义命令行的文件’,epilog=‘my - epilog’)
print(parse.print_help()) #使用命令行运行调用显示
#添加位置参数【必选参数】
parse.add_argument(‘name’,type=str,help=‘你自己的名字’)
parse.add_argument(‘age’,type=int,help=‘你的年龄’)
#添加可选参数
parse.add_argument(’-s’,’–sex’,type=str,help=‘你的性别’)
parse.add_argument(’-p’,’–pwd’,action=‘append’,type=str,help=‘编号’)
#action=‘append’ 可以接受多个参数
#限定一个范围
#default=‘男’ 默认参数
#choices=[‘男’,‘女’] 指定参数范围
parse.add_argument(’-s’,’–sex’,default=‘男’,choices=[‘男’,‘女’],type=str,help=‘你的性别’)
result=parse.parse_args()#开始解析参数
print(result)
print(result.name,result.age,result.sex)#打印参数
该博客介绍了如何使用Python的argparse模块创建自定义的命令行接口。通过示例展示了如何添加位置参数和可选参数,包括指定参数类型、默认值、范围限制等。文章还解释了参数解析过程和输出结果的展示。
238

被折叠的 条评论
为什么被折叠?



