码迷,mamicode.com
首页 > 编程语言 > 详细

python optparser模块学习

时间:2015-08-11 18:16:19      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

optparse是专门用来在命令行添加选项的一个模块。

首先来看一段示例代码

from optparse import OptionParser

MSG_USAGE = "myprog[ -f ][-s ] arg1[,arg2..]"

optParser = OptionParser(MSG_USAGE)

optParser.add_option("-f","--file",action = "store",type="string",dest = "fileName")

ooptParser.add_option("-v","--vison", action="store_false", dest="verbose",default=gggggg,

                     help="make lots of noise [default]")

fakeArgs = [-f,file.txt,-v,good luck to you, arg2, arge]

options, args = optParser.parse_args(fakeArgs)

print options.fileName

print options.verbose

print options

print args

print optParser.print_help()

输出结果为:

file.txt

False

{verbose: False, fileName: file.txt}

[this is some what, arg2, arge]

Usage: myprog[ -f ][-s ] arg1[,arg2..]

Options:

  -h, --help            show this help message and exit

  -f FILENAME, --file=FILENAME

  -v, --vison           make lots of noise [default]

基本使用步骤

1、 产生一个OptionParser的物件optParse。传入的值MSG_USAGE可被调用打印命令时显示出来。

MSG_USAGE = "myprog[ -f ][-s ] arg1[,arg2..]"

optParser = OptionParser(MSG_USAGE)

若要添加版本信息,初始化方式为:

optParser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")

2、 调用OptionParser.add_option()添加选项

optParser.add_option("-f","--file",action = "store",type = "string",dest = "fileName")

optParser.add_option("-v","--vison", action="store_false", dest="verbose",default=gggggg,

                     help="make lots of noise [default]")

add_option()参数说明:

   action:存储方式,分为三种store、store_false、store_true

   type:类型,指示参数的类型,如int,string

   dest:存储值的变量

   default:默认值

   help:帮助信息

3、 调用OptionParser.parse_args()剖析并返回一个directory和一个list。

fakeArgs = [-f,file.txt,-v,good luck to you, arg2, arge]

options, args = optParser.parse_args(fakeArgs)

print options.fileName

print options.verbose

print options

print args

输出结果

file.txt

False

{verbose: False, fileName: file.txt}

[this is some what, arg2, arge]

 

parse_args()说明:

如果没有传入参加,parse_args会默认将sys.argv[1:]的值作为默认参数。这里我们将   fakeArgs模拟输入的值。

从返回结果中可以看到:

    options为是一个directory,它的内容fakeArgs为“参数/值 ”的键值对。

    args 是一个list,它的内容是fakeargs除去options后,剩余的输入内容。

    options.version和options.fileName都取到与options中的directory的值。

4、 调用OptionParser.optParser.print_help()输出帮助信息

optParser.print_help()

显示返回结果

Usage: myprog[ -f ][-s ] arg1[,arg2..]

Options:

  -h, --help            show this help message and exit

  -f FILENAME, --file=FILENAME

  -v, --vison           make lots of noise [default]

从输出结果可以看出:

    • 最开始的的MSG_USAGE的值:在这个地方显示出来了。
    • 自动添加了-h这个参数。

注:在MSG_USAGE中如果使用%prog,会被自动解析为sys.args[0] 也就是文件名。如将,MSG_USAGE = "%prog [options] arg1 arg2",

假如文件名为   filexx,那么出现在help中的信息就是" filexx[options] arg1 arg2"。

5,处理异常

包括程序异常和用户异常。这里主要讨论的是用户异常,是指因用户输入无效的、不完整的命令行参数而引发的异常。optparse 可以自动探测并处理一些用户异常:

#!/usr/bin/env python

from optparse import OptionParser

parser = OptionParser()

parser.add_option("-v","--version",action="store_true",
    dest="verbose",default="fffffffffffffff")

parser.add_option("-n",action="store_false", type="int", dest="num")

args = ["-v","good luck to you","-n",abc,arg2,arge]
(options, args) = parser.parse_args(args)
print options.num

输出:

Traceback (most recent call last):
  File "parse_6.py", line 10, in <module>
    parser.add_option("-n",action="store_false", type="int", dest="num")
  File "D:\Python27\lib\optparse.py", line 1013, in add_option
    option = self.option_class(*args, **kwargs)
  File "D:\Python27\lib\optparse.py", line 578, in __init__
    checker(self)
  File "D:\Python27\lib\optparse.py", line 664, in _check_type
    "must not supply a type for action %r" % self.action, self)
optparse.OptionError: option -n: must not supply a type for action store_false

用户也可以使用 parser.error() 方法来自定义部分异常的处理:

(options, args) = parser.parse_args()  
    [...]  
    if options.a and options.b:  
        parser.error("options -a and -b are mutually exclusive")

上面的例子,当 -b 和 -b 命令行参数同时存在时,会打印出“options -a and -b are mutually exclusive“,以警告用户。

如果以上的异常处理方法还不能满足要求,你可能需要继承 OptionParser 类,并重载 exit() 和 erro() 方法。

 

 

深入分析OptionParser.add_option()的参数:

例:optParser.add_option("-v","--vison", action="store_false", dest="verbose",default=‘gggggg‘,

                     help="make lots of noise [default]")

action:

存储方式,分为三种store、store_false、store_true。

下面分别对三种方式进行说明:

第一种:action = "store"

1、如果输入的参数fakeArgs中存在"-v",则verbose返回的值为fakeArgs中的紧跟‘-v‘的数,即"good luck to you"。

这也正好options中的键值对应,剩下配对的参数都传给了args。请见以下代码

optParser.add_option("-f","--file",action = "store",type = "string",dest = "fileName")

optParser.add_option("-v","--vison", action="store", dest="verbose")

fakeArgs = [-f,file.txt,-v,good luck to you, arg2, arge]

options, args = optParser.parse_args(fakeArgs)

print optParse.verbose

print options

print args

输出结果

good luck to you

{verbose: good luck to you, fileName: file.txt}

[arg2, arge]

2、如果输入的参数fakeArgs中不存在"-v",则verbose的返回值为None。示例代码:

optParser.add_option("-f","--file",action = "store",type = "string",dest = "fileName")

optParser.add_option("-v","--vison", action="store", dest="verbose")

fakeArgs = [-f,file.txt,good luck to you, arg2, arge]

options, args = optParser.parse_args(fakeArgs)

print optParse.verbose

print options

print args

输出结果

None

{verbose: None, fileName: file.txt}

[good luck to you, arg2, arge]

第二种:action = "store_true"

1、fakeArgs中存在‘-v‘,verbose将会返回True而不是"good luck to you"。意思就是说verbose的值与‘-v‘

的后一位无关,只与‘-v‘存不存在就关。示例代码

optParser.add_option("-f","--file",action = "store",type = "string",dest = "fileName")

optParser.add_option("-v","--vison", action="store_true", dest="verbose")

fakeArgs = [-f,file.txt,-v,good luck to you, arg2, arge]

options, args = optParser.parse_args(fakeArgs)

print optParse.verbose

print options

print args

输出结果

True

{verbose: True, fileName: file.txt}

[good luck to you, arg2, arge]

2、fakeArgs中不存在‘-v‘,verbose同样返回空

运行代码:

optParser.add_option("-f","--file",action = "store",type = "string",dest = "fileName")

optParser.add_option("-v","--vison", action="store_true", dest="verbose")

fakeArgs = [-f,file.txt,good luck to you, arg2, arge]

options, args = optParser.parse_args(fakeArgs)

print optParse.verbose

print options

print args

输出结果:

None

{verbose: True, fileName: file.txt}

[good luck to you, arg2, arge]

第三种:action="store_false"

这与action="store_true"类似,只有其中有参数‘-v‘存在,则verbose的值为False,如果‘-v‘不存在,那么verbose的值为None。

第四种:action的值还可以取store_constappendcountcallback

具体用法请自行查看官方文档

 

default:

optParser.add_option("-v","--vison", action="store_false", dest="verbose",default=gggggg

default用于设置verbose的默认值。

如果action="store",default=‘gggggg‘,代码如下。

optParser.add_option("-v","--vison", action="store_false", dest="verbose",default=gggggg)

fakeArgs = [-f,file.txt,-v,good luck to you, arg2, arge]

如果fakeArgs中存在‘-v‘,则verbose返回值为False

如果不存在‘-v‘则返回值为,"gggggg"

如果action ="store_true",default=‘gggggg‘,代码如下。

optParser.add_option("-v","--vison", action="store_true", dest="verbose",default=gggggg

 

如果fakeArgs中存在‘-v‘,则返回值为True。

如果fakeArgs中不存在‘-v‘,则返回为"gggggg"

 

help:

optParser.add_option("-f","--file",action = "store",type = "string",dest = "fileName")

optParser.add_option("-v","--vison", action="store", dest="verbose",default=gggggg,

                     help="make lots of noise [default]")

主要用于显示帮助信息,使用optParser.print_help()将帮助栏显示出来。

在action="store"时,对比没使用help参数的‘-v‘与使用了help参数的‘-v‘,多了一行帮助信息。

Usage: myprog[ -f ][-s ] arg1[,arg2..]

Options:

  -h, --help            show this help message and exit

  -f FILENAME, --file=FILENAME

  -v VERBOSE, --vison=VERBOSE

                        make lots of noise [default]

注:如果help参数改为:help="make lots of noise [%default]",则可以使用default的默认值替换【%default】

type:

fakeArgs中所有的参数都必须是字符串,

type = “int”表示传递给此参数的值可以为“12”、“45”这样的,但不可以是“abc”;

type = “float”遵循的规则同上;

type = “string”表示传递给此参数的值为字符串;

同时,action和type是有对应关系的:若action=”store_false”或“store_true”存在, 则type不能存在;

 

参考文章:

http://www.cnblogs.com/captain_jack/archive/2011/01/11/1933366.html

http://blog.chinaunix.net/uid-15007890-id-3490627.html

python optparser模块学习

标签:

原文地址:http://www.cnblogs.com/python-life/p/4721611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!