argparse是python中用于解析命令行参数和选项的标准模块,它可以帮助我们轻松编写用户友好的命令行接口,它还会自动生成帮助和使用手册,并在用户给程序传入无效参数时报出错误信息
先看一段实例代码 test.py
import argparse from functools import reduce Calculator = { "add": lambda n: reduce(lambda x, y: x+y, n), "sub": lambda n: reduce(lambda x, y: x - y, n), "mul": lambda n: reduce(lambda x, y: x * y, n), "div": lambda n: reduce(lambda x, y: x / y, n), "rem": lambda n: reduce(lambda x, y: x % y, n), "pow": lambda n: reduce(lambda x, y: x ** y, n), "min": lambda n: min(n), "max": lambda n: max(n)} if __name__ == '__main__': parser = argparse.ArgumentParser(description="shadow's Calculator") parser.add_argument('-t', '--type', type=str, choices=['int', 'float'], help='return int or float', default='int') parser.add_argument('-m', '--mode', type=str, choices=['add', 'sub', 'mul', 'div', 'pow'], help='the mode of operation') # parser.add_argument('-n', '--nums', nargs='*', type=float, required=True, help='the nums of operation') parser.add_argument('-n', '--nums', nargs=2, type=float, required=True, help='the nums of operation') args = parser.parse_args() if args.mode: nums = args.nums print(eval(args.type)(Calculator[args.mode](nums))) else: print("Missing parameter '--mode'. Please choose from ['add', 'sub', 'mul', 'div', 'pow'].") exit(-1)看一下运行效果:
运行命令:python3 test.py -m add -n 2.3 3.4 获得结果:5 运行命令:python3 test.py -t float -m div -n 2.3 3.4 获得结果:0.676470588235294根据上需参数要求看错误的输入提示
注:argparse默认带–help/-h标签
帮助命令
运行命令:python3 test.py -h 提示:usage: test.py [-h] [-t {int,float}] [-m {add,sub,mul,div,pow}] -n NUMS NUMS shadow's Calculator optional arguments: -h, --help show this help message and exit -t {int,float}, --type {int,float} return int or float -m {add,sub,mul,div,pow}, --mode {add,sub,mul,div,pow} the mode of operation -n NUMS NUMS, --nums NUMS NUMS the nums of operation提示需要输入必选参数nums
运行命令:python3 test.py 提示:usage: test.py [-h] [-t {int,float}] [-m {add,sub,mul,div,pow}] -n NUMS NUMS test.py: error: the following arguments are required: -n/--nums提示需要需要输入参数2个
运行命令:python3 test.py -n 2 提示:usage: test.py [-h] [-t {int,float}] [-m {add,sub,mul,div,pow}] -n NUMS NUMS test.py: error: argument -n/--nums: expected 2 arguments提示需要需要输入参数2个
运行命令:python3 test.py -n 2 提示:usage: test.py [-h] [-t {int,float}] [-m {add,sub,mul,div,pow}] -n NUMS NUMS test.py: error: argument -n/--nums: expected 2 arguments提示nums参数类型不符
运行命令:python3 test.py -n 2 sss 提示:usage: test.py [-h] [-t {int,float}] [-m {add,sub,mul,div,pow}] -n NUMS NUMS test.py: error: argument -n/--nums: invalid float value: 'sss'执行程序中判断提示,缺少mode
运行命令:python3 test.py -n 2 3 提示:Missing parameter '--mode'. Please choose from ['add', 'sub', 'mul', 'div', 'pow'].提示mode参数不在可选范围内
运行命令:python3 test.py -n 2 3 -m sss 提示:usage: test.py [-h] [-t {int,float}] [-m {add,sub,mul,div,pow}] -n NUMS NUMS test.py: error: argument -m/--mode: invalid choice: 'sss' (choose from 'add', 'sub', 'mul', 'div', 'pow')parse_args() 默认使用的简单的类,用于创建一个保存属性的对象并返回该对象。 有时可能需要让ArgumentParser分配属性给一个已经存在的对象而不是一个新的Namespace对象。这可以通过指定namespace=关键字参数达到。
程序添加打印代码:print(args, type(args)) 运行命令:python3 test.py -n 2.3 3.4 -m sub 运行结果: Namespace(mode='sub', nums=[2.3, 3.4], type='int') <class 'argparse.Namespace'> -1可以自定义类然后设置给parser对象
class Shadow: pass s = Shadow() parser.parse_args(args=['--mode', 'add'], namespace=s)