pthon学习之argparse模块解析

本文详细介绍了Python的argparse模块,用于处理命令行参数和选项。通过add_argument()方法设置参数,使用parse_args()解析参数。argparse支持多种action,如store、store_true/false、append等。此外,还展示了如何处理非可选参数、自定义参数前缀、从配置文件读取参数以及自定义Action类等高级特性。
摘要由CSDN通过智能技术生成

  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]

 

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 --version

argparse_action.py 1.0

# 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       = []

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值