Python 命令行参数解析工具 argparse

为什么需要argparse#

开门见山,举一个简易计算器代码的例子,其中sys.argv用来读取脚本执行时后面传入的参数。

def calculator(x, y, operation): if "add" == operation: return x + y elif "mod" == operation: return x % y elif "sub" == operation: return x - y elif "div" == operation: return x / y elif "mul" == operation: return x * y def main(): print(calculator(sys.argv[1], sys.argv[2], sys.argv[3])) if __name__ == '__main__': main()

我们定义了一个calculator方法来完成一些简单的计算工作,这看来相当平凡,但对于用户来说,在没有良好的文档支持的前提下,传入不同参数有不同的行为,如果只有少量参数还可以接受,随着参数的增加,方法会变得越来越不易使用。这时候便需要参数解析,argparse模块便官方推荐的在optparse基础上更进一步的改良版标准库。让我们在了解一下她的庐山真面目之前先通过一个例子来了解argparse相关特性。

相信小伙伴们都或多或少用过Linux系统,让我们通过下面这个例子直观的了解argparse能做什么。

# 只输入ls,默认显示当前目录下内容 [root@host workarea]# ls Pythondemo scripts # 当我们给ls命令加一个参数,便会去找这个参数对应目录下的内容 [root@host workarea]# ls pythondemo/ arg1.py argparsedemo1.py fangzhen.py numpyapi.py tools # 我们也可以使用ls -[cmd]来改变行为,获得更详细的信息 [root@host workarea]# ls -l total 8 drwxr-xr-x 3 root root 4096 Dec 14 14:05 pythondemo drwxr-xr-x 2 root root 4096 Dec 14 14:29 scripts # 如果我们想知道ls命令的其他用法和相关信息可以使用ls --help [root@host workarea]# ls --help Usage: ls [OPTION]... [FILE]... List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. Mandatory arguments to long options are mandatory for short options too. -a, --all do not ignore entries starting with . -A, --almost-all do not list implied . and .. ...

脚本传入后的参数显示的绑定,让用户更清楚自己在执行什么操作,并且给用户一些提示信息在他忘记如何使用我们的脚本时,这便是我们要做的,当然如果参数数量不多,或者行为不复杂可以不使用。

argparse初体验# #总体使用流程如下 import argparse # 模板创建一个解析参数对象 parser = argparse.ArgumentParser() # 用来指定程序需要接受的命令参数 parser.add_argument() # 通过分析指定的参数返回一些数据 args = parser.parse_args()

我们直接试着用argparse对上面的例子进行改造,直观感受下区别

def calculator(args): operation = args.operation x = args.x y = args.y if "add" == operation: return x + y elif "mod" == operation: return x % y elif "sub" == operation: return x - y elif "div" == operation: return x / y elif "mul" == operation: return x * y def main(): parser = argparse.ArgumentParser() parser.add_argument("--x", type=float, default=1.0, help="What is the first number") parser.add_argument("--y", type=float, default=1.0, help="What is the second number") parser.add_argument("--operation", type=str, help="What operation? [add,mod,sub,div,mul]") args = parser.parse_args() print(args) print(calculator(args)) if __name__ == '__main__': main()

经过简单的改造,调用calculator方法时,我们可以更清楚自己在做什么操作,并且可以根据帮助信息使用而不需要去阅读源码了,这真的节省了很多不必要的时间。

# 直接调用不加参数,会提示None,命名空间那行为print(args) [root@host pythondemo]# python arg2.py Namespace(operation=None, x=1.0, y=1.0) None # 加上参数-h 或 --help我们就能看到帮助信息,感觉像模像样 [root@host pythondemo]# python arg2.py -h usage: arg2.py [-h] [--x X] [--y Y] [--operation OPERATION] optional arguments: -h, --help show this help message and exit --x X What is the first number --y Y What is the second number --operation OPERATION What operation? [add,mod,sub,div,mul] # 参数传入方法,这里的等于号可以省略 [root@host pythondemo]# python arg2.py --x=2 --y=3 --operation=mul 6.0 # 当我们少输入或者没有输入要求的参数 [root@host pythondemo]# python arg2.py 2 usage: arg2.py [-h] [--x X] [--y Y] [--operation OPERATION] arg2.py: error: unrecognized arguments: 2

当然这并没有完成我们的全部需求,我们还可以做的更好,那么我们就得深入了解下今天得主角argparse。

argparse详解# 模板创建argparse.ArgumentParser()#

我们可以给解析模板来个简单得标题,会在--help中显示

argparse.ArgumentParser(description='sample demo')

如果我们不想用Linux风格的"-"或"--"来作为命令前缀,我们自定义如下

parser = argparse.ArgumentParser(prefix_chars='-+/')

模板创建时是默认添加-h和--help帮助信息的,如果我们不想要,写可以去除掉

argparse.ArgumentParser(add_help=False)

我们也可以添加版本信息,会自动加入获取版本信息的-v和--version命令

argparse.ArgumentParser(version='1.0') 重头戏parser.add_argument()#

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/ec74f4086faf7a841961a593dc4aa571.html