argparse模块是Python的通用操作系统服务之一(Generic Opearating System Services),使用频繁,来看一看官方文档怎么写的。
16.4 argparse-Parser for command-line options,arguments, and sub-commands
16.4 argparse-命令行选项、参数、子命令解析器
The argparse module makes it easy to write user-friendly command-line
interfaces. The program defines what arguments ti requires, and
argparse will figure out how to parse those of sys.argv. The argparse
also automatically generates help and usage messages and issues errors
when users give the program invalid arguments.
argparse模块可以建立用户友好的命令行界面。程序可以定义参数的提交,argparse 将可以解析sys.argv的参数。当输入的程序的参数非法时,程序可以自动提供帮助信息。
16.4.1示例
下面的示例输入一系列整数,输出最大值或者求和值。这一模块的使用方法分为三步:
1、创建解析器(Creating a parser
import argparse
parser = argparse.ArgumentParser(description='Process some intergers')
2、增加参数(Adding arguments)
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulator', action='store_const',
const=sum, default=max, help='sum the integers(default: find the max')
3、解析参数(Parsing arguments)
args = parser.parse_args()
print(args.accumulator(args.integers))
使用示例:
>python prog.py 1 2 3 4 --sum
10
>python prog.py 1 2 3 4
4
以上内容翻译自《The Python Library Reference Release 3.7.3》P600