阅读原文点我
argparse模块作为optparse的一个替代被添加到Python2.7。argparse的实现支持一些不易于添加到optparse以及要求向后不兼容API变化的特性,因此以一个新模块添加到标准库。
与optparse相比较
argparse的API类似于optparse,甚至在很多情况下通过更新所使用的类名和方法名,使用argparse作为一个简单的替代。然而,有些地方在添加新特性时不能保持直接兼容性。
你必须视情况决定是否升级已有的程序。如果你已编写了额外的代码以弥补optparse的局限,也许你想升级程序以减少你需要维护的代码量。若argparse在所有部署平台上都可用,那么新的程序应尽可能使用argparse。
设置一个解析器
使用argparse的第一步就是创建一个解析器对象,并告诉它将会有些什么参数。那么当你的程序运行时,该解析器就可以用于处理命令行参数。
解析器类是 ArgumentParser 。构造方法接收几个参数来设置用于程序帮助文本的描述信息以及其他全局的行为或设置。
import argparse parser = argparse.ArgumentParser(description='This is a PyMOTW sample program')
定义参数
argparse是一个全面的参数处理库。参数可以触发不同的动作,动作由 add_argument() 方法的 action 参数指定。 支持的动作包括保存参数(逐个地,或者作为列表的一部分),当解析到某参数时保存一个常量值(包括对布尔开关真/假值的特殊处理),统计某个参数出现的次数,以及调用一个回调函数。
默认的动作是保存参数值。在这种情况下,如果提供一个类型,那么在存储之前会先把该参数值转换成该类型。如果提供 dest 参数,参数值就保存为命令行参数解析时返回的命名空间对象中名为该 dest 参数值的一个属性。
解析一个命令行
定义了所有参数之后,你就可以给 parse_args() 传递一组参数字符串来解析命令行。默认情况下,参数是从 sys.argv[1:]
中获取,但你也可以传递自己的参数列表。选项是使用GNU/POSIX语法来处理的,所以在序列中选项和参数值可以混合。
parse_args() 的返回值是一个命名空间,包含传递给命令的参数。该对象将参数保存其属性,因此如果你的参数 dest
是 "myoption"
,那么你就可以args.myoption
来访问该值。
简单示例
以下简单示例带有3个不同的选项:一个布尔选项(-a
),一个简单的字符串选项(-b
),以及一个整数选项(-c
)。
import argparse parser = argparse.ArgumentParser(description='Short sample app') parser.add_argument('-a', action="store_true", default=False) parser.add_argument('-b', action="store", dest="b") parser.add_argument('-c', action="store", dest="c", type=int) print parser.parse_args(['-a', '-bval', '-c', '3'])
有几种方式传递值给单字符选项。以上例子使用了两种不同的形式,-bval
和-c val
。
$ python argparse_short.py Namespace(a=True, b='val', c=3)
在输出中与'c'
关联的值是一个整数,因为程序告诉ArgumentParser在保存之前先转换该参数。
“长”选项名字,即选项的名字多于一个字符,以相同的方式进行处理。
import argparse parser = argparse.ArgumentParser(description='Example with long option names') parser.add_argument('--noarg', action="store_true", default=False) parser.add_argument('--witharg', action="store", dest="witharg") parser.add_argument('--witharg2', action="store", dest="witharg2", type=int) print parser.parse_args(['--noarg', '--witharg', 'val', '--withargs=3'])
结果也类似:
$ python argparse_long.py Namespace(noarg=True, witharg='val', witharg2=3)
argparse区别于optparse的一个地方是对非选项参数值的处理。optparse只进行选项解析,而argparse是一个全面的命令行参数解析工具,也处理非选项参数。
import argparse parser = argparse.ArgumentParser(description='Example with non-optional arguments') parser.add_argument('count', action="store", type=int) parser.add_argument('units', action="store") print parser.parse_args()
在这个例子中,“count”参数是一个整数,“units”参数存储为一个字符串。其中任意一个参数若没有在命令行中提供,或给定的值不能被转换为正确的类型,就会报告一个错误。
$ python argparse_arguments.py 3 inches Namespace(count=3, units='inches') $ python argparse_arguments.py some inches usage: argparse_arguments.py [-h] count units argparse_arguments.py: error: argument count: invalid int value: 'some' $ python argparse_arguments.py usage: argparse_arguments.py [-h] count units argparse_arguments.py: error: too few arguments
参数动作
argparse内置6种动作可以在解析到一个参数时进行触发:
store
保存参数值,可能会先将参数值转换成另一个数据类型。若没有显式指定动作,则默认为该动作。
store_const
保存一个被定义为参数规格一部分的值,而不是一个来自参数解析而来的值。这通常用于实现非布尔值的命令行标记。
store_ture
/store_false
保存相应的布尔值。这两个动作被用于实现布尔开关。
append
将值保存到一个列表中。若参数重复出现,则保存多个值。
append_const
将一个定义在参数规格中的值保存到一个列表中。
version
打印关于程序的版本信息,然后退出
import argparse parser = argparse.ArgumentParser() parser.add_argument('-s', action='store', dest='simple_value', help='Store a simple value') parser.add_argument('-c', action='store_const', dest='constant_value', const='value-to-store', help='Store a constant value') parser.add_argument('-t', action='store_true', default=False, dest='boolean_switch', help='Set a switch to true') parser.add_argument('-f', action='store_false', default=False, dest='boolean_switch', help='Set a switch to false') parser.add_argument('-a', action='append', dest='collection', default=[], help='Add repeated values to a list') parser.add_argument('-A', action='append_const', dest='const_collection', const='value-1-to-append', default=[], help='Add different values to list') parser.add_argument('-B', action='append_const', dest='const_collection', const='value-2-to-append', help='Add different values to list') parser.add_argument('--version', action='version', version='%(prog)s 1.0') results = parser.parse_args() print 'simple_value =', results.simple_value print 'constant_value =', results.constant_value print 'boolean_switch =', results.boolean_switch print 'collection =', results.collection print 'const_collection =', results.const_collection
$ python argparse_action.py -h usage: argparse_action.py [-h] [-s SIMPLE_VALUE] [-c] [-t] [-f] [-a COLLECTION] [-A] [-B] [--version] optional arguments: -h, --help show this help message and exit -s SIMPLE_VALUE Store a simple value -c Store a constant value -t Set a switch to true -f Set a switch to false -a COLLECTION Add repeated values to a list -A Add different values to list -B Add different values to list --version show program's version number and exit $ python argparse_action.py -s value simple_value = value constant_value = None boolean_switch = False collection = [] const_collection = [] $ python argparse_action.py -c simple_value = None constant_value = value-to-store boolean_switch = False collection = [] const_collection = [] $ python argparse_action.py -t simple_value = None constant_value = None boolean_switch = True collection = [] const_collection = [] $ python argparse_action.py -f simple_value = None constant_value = None boolean_switch = False collection = [] const_collection = [] $ python argparse_action.py -a one -a two -a three simple_value = None constant_value = None boolean_switch = False collection = ['one', 'two', 'three'] const_collection = [] $ python argparse_action.py -B -A simple_value = None constant_value = None boolean_switch = False collection = [] const_collection = ['value-2-to-append', 'value-1-to-append'] $ python argparse_action.py --version argparse_action.py 1.0
选项前缀
argparse选项的默认语法是基于Unix约定的,使用一个“-”前缀来表示命令行开关。argparse支持其他前缀,因此你可以使得你的程序遵照本地平台的默认语法(例如,在Window上使用“/”)或者遵循不同的约定。
import argparse parser = argparse.ArgumentParser(description='Change the option prefix charaters', prefix_chars='-+/') parser.add_argument('-a', action="store_false", default=None, help='Turn A off') parser.add_argument('+a', action="store_true", default=None, help='Turn A on') parser.add_argument('//noarg', '++noarg', action="store_true", default=False) print parser.parse_args()
将ArgumentParser 方法的prefix_chars 参数设置为一个字符串,该字符串包含所有允许用来表示选项的字符。需要理解的是虽然prefix_chars包含允许用于开关的字符,但单个参数定义只能使用一种给定的开关语法。这让你可以对使用不同前缀的选项是否是别名(比如独立于平台的命令行语法的情况)或替代选择(例如,使用“+”表明打开一个开发,“-”则为关闭一个开关)进行显式地控制。在上述例子中,+a
和-a
是不同的参数,//noarg
也可以 ++noarg
提供,但不是 --noarg
。
$ python argparse_prefix_chars.py -h usage: argparse_prefix_chars.py [-h] [-a] [+a] [//noarg] Change the option prefix characters optional arguments -h, --help show this help message and exit -a Turn A off +a Turn A on //noarg,++noarg $ python argparse_prefix_chars.py +a Namespace(a=True, noarg=False) $ python argparse_prefix_chars.py -a Namespace(a=False, noarg=False) $ python argparse_prefix_chars.py //noarg Namespace(a=None, noarg=True) $ python argparse_prefix_chars.py ++noarg Namespace(a=None, noarg=True) $ python argparse_prefix_chars.py --noarg usage: argparse_prefix_chars.py [-h] [-a] [+a] [//noarg] argparse_prefix_chars.py: error: unrecognized arguments: --noarg
凑字数