Python argparse命令行参数解析

Python argparse命令行参数解析教程

Python 的 argparse 模块是用于解析命令行选项和参数的标准模块,argparse 还可以自动的生成 help 和 usage 信息,当程序的参数无效时,它可以自动生成错误信息。

Python argparse模块解析命令行详解

语法

import argparse  #导入模块 parser = argparse.ArgumentParser() parser.add_argument()  parser.parser_args() 

说明

首先,使用 ArgumentParser() 创建解析对象,接着,使用 add_argument 向该对象中添加使用到的命令行选项和参数,最后,使用 parser_args 解析命令行。

argparse.ArgumentParser()

使用 argparse 的第一步是创建 ArgumentParser 对象,ArgumentParser 对象保存了所有必要的信息,用以将命令行参数解析为相应的 Python 数据类型。比如:

parser = argparse.ArgumentParser(description='Process some integers.')

parser.add_argument()

调用 add_argument()向 ArgumentParser 对象添加命令行参数信息,这些信息告诉 ArgumentParser 对象如何处理命令行参数。可以通过调用 parse_agrs() 来使用这些命令行参数。例如:

parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')

parser.parse_args()

通过调用parse_args()来解析ArgumentParser对象中保存的命令行参数:将命令行参数解析成相应的数据类型并采取相应的动作,它返回一个Namespace对象。

parser.parse_args(['--sum', '7', '-1', '42'])

在实际的 python 脚本中,parse_args() 一般并不使用参数,它的参数由 sys.argv 决定。

ArgumentParser对象

class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, argument_default=None, conflict_handler=’error’, add_help=True, allow_abbrev=True)

ArgumentParser参数

参数 描述
prog 程序文件名。
usage 程序使用说明。
description 程序目的说明。
epilog 程序说明后记。
parents ArgumentParser 对象的父对象的参数列表。
formatter_class help 信息的说明格式
prefix_chars 命令行参数的前缀。
argument_default 参数的全局默认值。
conflict_handler 冲突处理。
add_help 是否增加 help 选项。
allow_abbrev 是否使用参数的缩写。

案例

获取所有命令行

使用 argparse 模块获取命令行

import argparse print("嗨客网(www.haicoder.net)") parser = argparse.ArgumentParser(usage="it's usage tip.", description="help info.") parser.add_argument("--address", default=80, help="the port number.", dest="code_address") parser.add_argument("--fg", choices=['.jpg', '.png'], default=".jpg", help="the file type") parser.add_argument("--port", type=int, required=True, help="the port number.") parser.add_argument("-l", "--log", default=False, action="store_true", help="active log info.") args = parser.parse_args()

我们不输入任何参数,程序运行后,控制台输出如下:

77_python命令行参数解析argparse.png

我们使用 argparse 模块的 add_argument 函数增加了四个命令行参数,第一个是 address 参数,该参数的默认值是 80。第二个参数是 fg 参数,该参数的选项只能从后面的 choices 列表中选择。

第三个参数是 port 参数,该参数的类型是 int,是一个必选参数,最后一个参数是短参数,默认值是 False

我们不带任何参数,运行该程序,该程序报没有必选参数 port 的错误,因此,我们加上 port 选项,再次运行,控制台输出如下:

78_python命令行参数解析argparse.png

此时,程序不再报错,我们再次增加一个 fg 选项,再次运行程序,控制台输出如下:

79_python命令行参数解析argparse.png

我们看到,我们输入的 fg 选项,不再程序指定的 fg 参数的选项里面,因此,程序报错。

获取命令行参数值

使用 argparse 模块获取命令行参数值

import argparse print("嗨客网(www.haicoder.net)") parser = argparse.ArgumentParser(usage="it's usage tip.", description="help info.") parser.add_argument("--address", default=80, help="the port number.", dest="code_address") parser.add_argument("--fg", choices=['.jpg', '.png'], default=".jpg", help="the file type") parser.add_argument("--port", type=int, required=True, help="the port number.") parser.add_argument("-l", "--log", default=False, action="store_true", help="active log info.") args = parser.parse_args() print("port value =", args.port) print("fg value =", args.fg)

我们不输入任何参数,程序运行后,控制台输出如下:

80_python命令行参数解析argparse.png

当我们运行指定参数之后,使用 parse_args 的返回值就可以访问我们指定的参数的值。

Python argparse命令行参数解析总结

import argparse parser = argparse.ArgumentParser() parser.add_argument()  parser.parser_args()