pthon学习之argparse模块解析

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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: argparsePython标准库中的一个命令行解析模块。它可以自动生成帮助和使用信息,并且支持默认值、可选参数、位置参数等。 下面是一个简单的使用argparse的例子: ```python import argparse parser = argparse.ArgumentParser(description='A simple argparse example') parser.add_argument('-n', '--name', type=str, help='Your name') parser.add_argument('-a', '--age', type=int, help='Your age') args = parser.parse_args() print('Hello,', args.name, 'your age is', args.age) ``` 运行上面的代码后,可以通过命令行来传入参数,如: ``` python test.py -n John -a 30 ``` 这样就能在程序中得到参数name和age的值,输出: ``` Hello, John your age is 30 ``` argparse模块还支持其他选项,如添加默认值、设置参数为可选或必选等,详见官方文档。 ### 回答2: argparsePython中的一个命令行参数解析模块。它可以用来解析命令行参数以及生成用于帮助文档的用户友好的提示信息。 使用argparse模块可以轻松定义和解析命令行参数。下面是一个argparse的简单实例: 假设我们要编写一个程序来计算两个数字的和。我们希望能够从命令行传递这两个数字作为参数,并且能够选择是否将计算结果打印出来。 首先,我们需要导入argparse模块,然后创建一个ArgumentParser对象: import argparse parser = argparse.ArgumentParser() 然后,我们可以使用add_argument()方法来定义我们需要的参数: parser.add_argument("num1", type=int, help="第一个数字") parser.add_argument("num2", type=int, help="第二个数字") parser.add_argument("-p", "--print", action="store_true", help="打印计算结果") 在这个例子中,我们使用add_argument()方法定义了两个位置参数num1和num2,分别表示第一个数字和第二个数字。我们还使用了一个可选参数--print(简写为-p),用来表示是否打印计算结果。action="store_true"表示如果命令行中指定了--print参数,则将其存储为True,否则为False。 接下来,我们需要使用parse_args()方法来解析命令行参数: args = parser.parse_args() 现在,我们可以使用args对象来访问用户输入的参数了: sum_result = args.num1 + args.num2 if args.print: print("计算结果:", sum_result) 最后,我们可以将上述代码保存为一个Python脚本文件,然后在命令行中运行该文件,并传递两个数字和可选的--print参数来测试程序的功能,例如: python calculator.py 2 3 --print 以上就是argparse模块解析和实例的简单介绍。这个模块非常灵活和强大,可以用于处理各种类型的命令行参数,包括位置参数、可选参数、默认值等等。它还可以生成用户友好的帮助文档,以方便用户使用程序。 ### 回答3: Pythonargparse模块是一个用于解析命令行参数的库。它可以帮助我们在命令行中传递参数,并且提供了一些额外的功能,比如生成帮助信息和错误提示。 使用argparse模块非常简单。我们首先需要导入argparse库,然后创建一个ArgumentParser对象。然后,我们可以使用add_argument()方法来添加我们需要的命令行参数。 add_argument()方法有很多参数可以配置,比如name或flags指定参数的名称,type指定参数的类型,default指定参数的默认值等等。我们可以根据我们的具体需求来配置这些参数。 当命令行参数被定义后,我们可以通过parse_args()方法来解析命令行参数。这个方法会返回一个包含解析后的参数的命名空间对象,我们可以使用这个对象的属性来访问具体的参数值。 下面是一个使用argparse模块的简单示例: ```python import argparse # 创建ArgumentParser对象 parser = argparse.ArgumentParser(description='这是一个解析命令行参数的示例') # 添加命令行参数 parser.add_argument('name', type=str, help='你的名字') parser.add_argument('age', type=int, help='你的年龄') # 解析命令行参数 args = parser.parse_args() # 访问参数值 print('你好,{},你的年龄是{}岁。'.format(args.name, args.age)) ``` 在上面的示例中,我们创建了一个ArgumentParser对象,并添加了两个命令行参数:name和age。然后我们解析命令行参数,并使用args对象访问参数值并打印出来。 当我们在命令行中运行这个脚本时,我们需要在脚本名称后面提供两个参数,即我们的名字和年龄。比如: ``` $ python script.py Alice 25 ``` 这样,脚本就会打印出:`你好,Alice,你的年龄是25岁。`

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值