python 小知识--- 解析命令行参数模块argparse

tech2025-12-07  9

argparse

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对象,description参数可以用于插入描述脚本用途的信息,可以为空 parser = argparse.ArgumentParser(description="shadow's Calculator") # 添加 --type标签,标签别名可以为 -t,help参数用于描述参数的用途或意义, type:输入参数的类型,choices:可选的参数值 default:默认值 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=2, type=float, required=True, help='the nums of operation') # 将变量以标签-值的字典形式存入args namespace args = parser.parse_args() 位置参数’-t’, ‘–type’: 分别表示 --type标签和标签别-thelp: 参数用于描述参数的用途或意义type: 输入参数的类型choices:可选的参数值required: 为True表示必选参数nargs:限定输入参数个数 ‘*’: 之后所有的输入都将作为该位置参数的值‘+’: 表示读取至少1个该位置参数’?’:表示该位置参数要么没有,要么就只要一个 action:指出应该如何处理命令行参数(支持的操作:’store’ ,’store_const’,’store_true’,’store_false’,’append’,’append_const’,’count’,’help’,’version’) 互斥参数:action=‘store_true’,同一组下的参数只能使用一个

根据上需参数要求看错误的输入提示

注: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')

argparse.Namespace

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)
最新回复(0)