Tommonkey

All greatness comes from a brave beginning

0%

Python-argparse模块

最近在GitHub上欣赏别人写的代码,发现一个常用的模块–argparse,居然我到现在才知道,简直是罪过,于是马上开始了这个模块用法的学习,这样后面我在写的时候就可以摈弃input()函数来交互了。这个模块是python内置所有是不需要安装的,我们直接import即可。

argparse模块的功能

该模块可以在命令模式下完成使用者与程序之间的参数交互,并且这个模块会自动生成help菜单,让使用者可以通过 -h|–help查看程序的使用方法等。

使用方法

这里主要分四步:

  • import导入该模块:import argparse
  • 创建解析器对象:parse = argparse.ArgumenParser()
  • 添加需要的命令行参数与选项:parse.add_argument()
  • 解析:parse.parse_args()
    这里主要介绍一下第二,三步中这两个方法的使用。
    先贴出argparse.ArgumenParser()中的可选参数及其含义:
    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 | 是否支持长参数 |
    parse.add_argument()中的可选参数及其含义:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    | 名字            | 功能                                            |
    | --------------- | ---------------------------------------------------------- |
    | action | 匹配到后的行为,如action="store_true",设置为布尔值为true |
    | nargs | 选项跟随的个数 |
    | default | 设置默认值 |
    | type | 设置参数的类型 |
    | choices | 设置参数值范围 |
    | requred | 设置参数是否为必选项 |
    | dest | 设置help中显示的参数名和名字空间中的属性值名 |

实列

这里贴出我写的简单列子来辅助说明该模块的使用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# author:Tommonkey
# date:2022/5/4

import sys
import argparse

def arg_parse():
# 构造解析器
parse = argparse.ArgumentParser(prog="test.py",usage="huw to use this program",description="this just a test,don't worry!")
# 添加参数
# dest值设置namespace中属性值的名称
parse.add_argument("-n","--name",dest="name",type=str,default="****",required=False,help="output you name")
parse.add_argument("-b","--birthday",dest="bir",type=str,default="2000/1/1",required=False,help="output you birthday")
# metavar:定制help选项带的参数名,只影响help的输出,跟dest不一样
parse.add_argument("-p","--phone",metavar="hahaha",required=False,help="output your phone")
parse.add_argument("-i", "--info",action="store_true",help="output you info")
# 解析
result = parse.parse_args()
return result


if __name__ == "__main__":
obj = arg_parse()
# 通过sys.argv[]列表读取命令行下运行py程序时的参数,这里是首先获取参数的个数
print(len(sys.argv))
# 打印输出第三个参数,即打印名字
print(sys.argv[2])
# 打印名字空间,可查看 属性名:值
print(obj)
# 通过属性值来调用其值
print(obj.name,obj.bir)
print(obj.phone)
print(obj.info)

命令行启动该py文件的结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
PS D:\Work_pycharm> python .\1.py -h  
usage: huw to use this program

this just a test,don't worry!

optional arguments:
-h, --help show this help message and exit
-n NAME, --name NAME output you name
-b BIR, --birthday BIR
output you birthday
-p hahaha, --phone hahaha
output your phone
-i, --info output you info
PS D:\Work_pycharm> python .\1.py -n tommonkey
3
tommonkey
Namespace(bir='2000/1/1', info=False, name='tommonkey', phone=None)
tommonkey 2000/1/1
None
False
PS D:\Work_pycharm>

奖励作者买杯可乐?