命令行解析工具 Argparse介绍

我们从一个基本的程序开始(它什么也不做)

import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

运行结果:
$ python prog.py
$ python prog.py --help
usage: prog.py [-h]

optional arguments:
  -h, --help  show this help message and exit
$ python prog.py --verbose
usage: prog.py [-h]
prog.py: error: unrecognized arguments: --verbose
$ python prog.py foo
usage: prog.py [-h]
prog.py: error: unrecognized arguments: foo


结果分析:

  • 若不给参数而运行这个程序,将不会得到任何结果。
  • 第二条命名显示了使用的argparse的好处,你什么也没做,却得到了一个很好的帮助信息。
  • 我们无需人为设置--help参数,就能得到一个良好的帮助信息。但是若给其他参数(比如foo)就会产生一个错误。

位置参数

   首先,给一个例子:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print args.echo

运行结果:

$ python prog.py
usage: prog.py [-h] echo
prog.py: error: the following arguments are required: echo
$ python prog.py --help
usage: prog.py [-h] echo

positional arguments:
  echo

optional arguments:
  -h, --help  show this help message and exit
$ python prog.py foo
foo

结果分析:

  • 这次,我们增加了一个add_argument()方法,用来设置程序可接受的命令行参数。
  • 现在要运行程序,就必须设置一个参数。
  • parse_args()方法实际上从我们的命令行参数中返回了一些数据,在上面的例子中是echo
  • 这个像“魔法”一样的过程,是argparse自动完成的。

尽管自动产生的帮助信息展示地很美观,但是我们仍然无法只根据echo这个参数知道它是做什么的。所以,我们增加了一些东西,使得它变得更有用。

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print args.echo

运行结果:

$ python prog.py -h
usage: prog.py [-h] echo

positional arguments:
  echo        echo the string you use here

optional arguments:
  -h, --help  show this help message and exit

在此基础上,我们再多改变一点:(计算输入参数square的平方)

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number")
args = parser.parse_args()
print args.square**2

     
     

下面是运行结果:

$ python prog.py 4
Traceback (most recent call last):
  File "prog.py", line 5, in <module>
    print args.square**2
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'


这个程序并不能正确运行,因为argparse会将输入当作字符串处理,所以我们需要设置它的类型:(type=int)


import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
                    type=int)
args = parser.parse_args()
print args.square**2

      
      

      
      

下面是运行结果:

$ python prog.py 4
16
$ python prog.py four
usage: prog.py [-h] square
prog.py: error: argument square: invalid int value: 'four'

现在,这个程序能够顺利运行,而且能够处理一些错误输入。



      
      
>>> >>> help(argparse.ArgumentParser.add_argument)
Help on method add_argument in module argparse:


add_argument(self, *args, **kwargs) unbound argparse.ArgumentParser method
    add_argument(dest, ..., name=value, ...)
    add_argument(option_string, option_string, ..., name=value, ...)

      
      
dest: 参数在程序中对应的变量名称 add_argument("a",dest='code_name')

default: 参数默认值

help: 参数作用解释  add_argument("a", help="params means")

type : 默认string  add_argument("c", type=int)

action:
    store:默认action模式,存储值到指定变量。
    store_const:存储值在参数的const部分指定,多用于实现非布尔的命令行flag。
    store_true / store_false:布尔开关。可以2个参数对应一个变量。
    append:存储值到列表,该参数可以重复使用。
    append_const:存储值到列表,存储值在参数的const部分指定。
    count: 统计参数简写输入的个数  add_argument("-c", "--gc", action="count")
    version 输出版本信息然后退出。
const:配合action="store_const|append_const"使用,默认值
choices:输入值的范围 add_argument("--gb", choices=['A', 'B', 'C', 0])

      
      

      
      
补充链接
http://www.cnblogs.com/captain_jack/archive/2011/01/11/1933366.html










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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值