最近在GitHub上欣赏别人写的代码,发现一个常用的模块–argparse,居然我到现在才知道,简直是罪过,于是马上开始了这个模块用法的学习,这样后面我在写的时候就可以摈弃input()函数来交互了。这个模块是python内置所有是不需要安装的,我们直接import即可。
argparse模块的功能
该模块可以在命令模式下完成使用者与程序之间的参数交互,并且这个模块会自动生成help菜单,让使用者可以通过 -h|–help查看程序的使用方法等。
使用方法
这里主要分四步:
- import导入该模块:import argparse
- 创建解析器对象:parse = argparse.ArgumenParser()
- 添加需要的命令行参数与选项:parse.add_argument()
- 解析:parse.parse_args()
这里主要介绍一下第二,三步中这两个方法的使用。
先贴出argparse.ArgumenParser()中的可选参数及其含义:parse.add_argument()中的可选参数及其含义:1
2
3
4
5
6
7
8
9
10
11| 名字 | 默认值 | 功能 |
| --------------- | ------------------- | ----------------------------------------------- |
| prog | sys.argv\[0\] | `-h`时显示的程序名 |
| usage | - | usage字段描述 |
| description | None | description字段描述 |
| epilog | None | 补充字段描述 |
| parents | None | 从父(公共)解析器中继承所有的参数选项 |
| formatter_class | None | 定制说明文本的显示风格 |
| prefix_class | - | 定制前缀字符,例如前缀**"-b"**改为**“+b"** |
| add_help | True | 是否使能显示参数 `-h --help` |
| allow_abbrev | True | 是否支持长参数 |1
2
3
4
5
6
7
8
9| 名字 | 功能 |
| --------------- | ---------------------------------------------------------- |
| action | 匹配到后的行为,如action="store_true",设置为布尔值为true |
| nargs | 选项跟随的个数 |
| default | 设置默认值 |
| type | 设置参数的类型 |
| choices | 设置参数值范围 |
| requred | 设置参数是否为必选项 |
| dest | 设置help中显示的参数名和名字空间中的属性值名 |
实列
这里贴出我写的简单列子来辅助说明该模块的使用方法
1 | # author:Tommonkey |
命令行启动该py文件的结果:
1 | PS D:\Work_pycharm> python .\1.py -h |