当前位置:编程学习 > 网站相关 >>

python模块介绍- argparse:命令行选项及参数解析

python模块介绍- argparse:命令行选项及参数解析
2012-08-20磁针石

#承接软件自动化实施与培训等gtalk:ouyangchongwu#gmail.com qq 37391319 博客: http://blog.csdn.net/oychw

#版权所有,转载刊登请来函联系

#自动化测试和python群组: http://groups.google.com/group/automation_testing_python

#参考资料:《The Python Standard Library by Example》

#实验环境:Python 2.7.3 CentOS release 6.2(Final) 32bits

 

 

 

14.3 argparse:命令行选项及参数解析
作用:命令行选项及参数解析。

Python版本:2.7及以后版本

argparse模块于Python2.7引入,旨在替换optparse。

14.3.1建立解析器
import argparse

parser = argparse.ArgumentParser(

description=’This is a PyMOTW sample program’,

)      

argparse是一个完整的参数处理库。参数可以根据add_argument()的action选项触发不同action。支持的action有存储参数(单个,或作为列表的一部分);存储常量的值(对布尔开关true/false有特殊处理)。默认动作是存储参数值。支持type(指定存储类型)和dest(指定存储变量)等参数。

然后使用函数parse_args()进行参数解析,这个函数的输入默认是sys.argv[1:],也可以使用其他字符串列表。选项使用GNU/POSIX语法处理,可以混合选项和参数值。parse_args的返回值是一个包含命令参数的Namespace。所有参数以属性的形式存在,比如args.myoption。

下面是一个简单的示例:

import argparse

 

parser = argparse.ArgumentParser(description='Short sampleapp')

 

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'])

    执行结果:

# pythonargparse_short.py

Namespace(a=True, b='val', c=3)

 

长参数也可以进行同样处理:

import argparse

 

parser = argparse.ArgumentParser(

    description='Examplewith 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', '--witharg2=3' ]

    )

    执行结果:

# python argparse_long.py

Namespace(noarg=True, witharg='val', witharg2=3)

 

不同于optparse,argparse可以很好地处理非可选参数(没有’-‘等开头的参数):

import argparse

 

parser = argparse.ArgumentParser(

    description='Examplewith nonoptional arguments',

    )

 

parser.add_argument('count', action="store",type=int)

parser.add_argument('units', action="store")

 

print parser.parse_args()

    没有指定类型的,默认是字符串。执行结果:

# python argparse_arguments.py 3inches

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 intvalue: 'some'

# python argparse_arguments.py

usage: argparse_arguments.py [-h] count units

argparse_arguments.py: error: too few arguments

 

参数action有:

store:默认action模式,存储值到指定变量。

store_const:存储值在参数的const部分指定,多用于实现非布尔的命令行flag。

store_true / store_false:布尔开关。可以2个参数对应一个变量。

append:存储值到列表,该参数可以重复使用。

append_const:存储值到列表,存储值在参数的const部分指定。

version 输出版本信息然后退出。

下面是各种action的示例:

import argparse

 

parser = argparse.ArgumentParser()

 

parser.add_argument('-s', action='store',

                   dest='simple_value',

                    help='Storea 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',

            &n

补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,