1. argparse介绍
是python的一个命令行解析包,用于编写可读性非常好的程序
2.基本用法
eg:
#导包
import argparse
#创建paser对象
parser = argparse.ArgumentParser()
#传参
parser.add_argument('-s','--show',action='store_true',help="you want show the result or not")
#创建读取对象
args=parser.parse_args()
#读取参数
isShow=args.show
3.positional arguments(必选参数)
调用
python ***.py xxx
eg:
#传参
parser.add_argument("echo")
#取参
x=args.echo
4. optional arguments(可选参数)
调用
python ***.py -s 123
或者
python ***.py --show 123
eg:
parser.add_argument('-s','--show',help="you want show the result or not")
x=args.show
5.action='store_true'
调用
python ***.py -s #代表show的值为true
或者
python ***.py #代表show的值为false
eg:
parser.add_argument('-s','--show',action='store_true',help="you want show the result or not")
isShow=args.show
6. 类型 type
默认的参数类型为str,如果要进行数学计算,需要对参数进行解析后进行类型转换。
eg:
parser.add_argument('x', type=int, help="the base")
x=args.x
7. 可选值choices=[]
限定其取值范围为[xx,yy,zz,...]
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2], help="increase output verbosity")
8.显示help信息
python xxx.py -h 或者 python xxx.py --help
9.默认参数
defalut
parser.add_argument("-v", "--verbosity", type=int, default=1, help="increase output verbosity")
如果内容有帮助到您,希望大家多多点赞+收藏+关注!!!
经常会在知乎中分享自己的学习笔记,和大家一起学习进步!!!
有问题大家可以在评论区打出,一定及时给大家回复!!!
笔记链接:有道云笔记note.youdao.com