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

#承接软件自动化实施与培训等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',

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    = %r' % results.simple_value

print 'constant_value  = %r' % results.constant_value

print 'boolean_switch  = %r' % results.boolean_switch

print 'collection      = %r' % results.collection

print 'const_collection = %r' % results.const_collection

执行结果:

# python argparse_action.py -h

usage: argparse_action.py [-h] [-s SIMPLE_VALUE] [-c] [-t][-f]

[-a COLLECTION] [-A] [-B] [--version]

opt

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值