FreezeJ' Blog

python argparse用法

2020-10-29

官方教程: https://docs.python.org/zh-cn/3/howto/argparse.html
完整api:https://docs.python.org/zh-cn/3/library/argparse.html

引入argparse库

import argparse

创建解析器

# 以下是一个常用的参数例子
parser = argparse.ArgumentParser(
    description='命令描述',  # 命令描述
    epilog="注意xxxxxx",  # 备注
    allow_abbrev=False,  # 关闭参数缩写,避免歧义
    # formatter_class=argparse.ArgumentDefaultsHelpFormatter),  # 自动添加默认的值的信息到每一个帮助信息的参数中
    # add_help=False,  # 关闭默认的帮助
    )

输出结果:

parser.print_help()
usage: arg.py [-h]

命令描述

optional arguments:
  -h, --help  show this help message and exit

注意xxxxxx

解析器完整参数

添加参数

# 位置参数(必填参数)
parser.add_argument('infile_list', nargs='+', help="接受一个以上的文件名")
parser.add_argument('outfile', type=argparse.FileType('w'), help="输出到一个文件")
# 可选参数(不是必填的参数)
parser.add_argument('-h', '--help',help='显示帮助信息', action='help')
parser.add_argument('--debug', action='store_true', help='开启debug模式,默认:%(default)s')
parser.add_argument('--max_worker', metavar="N", type=int, default=5,choices=range(1,11), help='最大线程数,默认:%(default)s,可选:%(choices)s')
parser.add_argument('--reload', dest='operate_list', action='append_const', const='reload', help='重载操作')
parser.add_argument('--restart', dest='operate_list', action='append_const', const='restart', help='重启操作')

备注:

metavar 表示预期的参数
可以在 help文本里面使用 %(xxx)s来引用对应的变量值,如 %(choices)s%(default)s%(type)s%(required)s

完整参数解析

常用action

store 存储参数的值,这是默认的动作.
store_const 存储被 const 命名参数指定的值。
store_true store_false 分别用作存储 TrueFalse 值。
append 存储一个列表,并且将每个参数值追加到列表中。
count 计算一个关键字参数出现的数目或次数。
help 打印所有当前解析器中的选项和参数的完整帮助信息,然后退出。

nargs

关联不同数目的命令行参数到单一动作。
N (一个整数)。命令行中的 N 个参数会被聚集到一个列表中。
? 0个或1个,没有使用默认值
* 所有当前命令行参数被聚集到一个列表中。
+ 1个或多个

解析参数

ArgumentParser.parse_args(args=None, namespace=None)
args - 要解析的字符串列表。 默认值是从 sys.argv 获取。
namespace - 用于获取属性的对象。 默认值是一个新的空 Namespace 对象。

其它

互斥:
ArgumentParser.add_mutually_exclusive_group(required=False)

打印帮助:
ArgumentParser.print_usage(file=None)
ArgumentParser.print_help(file=None)
ArgumentParser.format_usage()
ArgumentParser.format_help()

完整例子

import sys
import argparse

# 创建解析器
parser = argparse.ArgumentParser(
    description='命令描述',  # 命令描述
    epilog="注意xxxxxx",  # 备注
    allow_abbrev=False,  # 关闭参数缩写,避免歧义
    # formatter_class=argparse.ArgumentDefaultsHelpFormatter),  # 自动添加默认的值的信息到每一个帮助信息的参数中
    add_help=False,  # 关闭默认的帮助
    )

# 添加参数
# 位置参数(必填参数)
parser.add_argument('infile', nargs='+', help="接受一个以上的文件名")
parser.add_argument('outfile', type=argparse.FileType('w'), default=sys.stdout, help="输出到一个文件")
# 可选参数(不是必填的参数)
parser.add_argument('-h', '--help',help='显示帮助信息', action='help')
parser.add_argument('-d', '--debug', action='store_true', help='开启debug模式,默认:%(default)s')
parser.add_argument('--max_worker', metavar="N", type=int, default=5, choices=range(1,11), help='最大线程数,默认:%(default)s,可选:%(choices)s')
parser.add_argument('--reload', dest='operate_list', action='append_const', const='reload', help='重载操作')
parser.add_argument('--restart', dest='operate_list', action='append_const', const='restart', help='重启操作')

# 解析参数
args = parser.parse_args()
usage: test.py [-h] [-d] [--max_worker N] [--reload] [--restart]
               infile [infile ...] outfile

命令描述

positional arguments:
  infile          接受一个以上的文件名
  outfile         输出到一个文件

optional arguments:
  -h, --help      显示帮助信息
  -d, --debug     开启debug模式,默认:False
  --max_worker N  最大线程数,默认:5,可选:1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  --reload        重载操作
  --restart       重启操作

注意xxxxxx

输出信息:

随手记

看ansible的源码时候,看到它是把一些公共的参数独立出来,写成一个模块,后续按需引入的,这种写法对于一个比较复杂的命令,可读性和复用也会更加好。

Tags: Python