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)

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:类型(我也不知道什么的类型)

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模拟输入的值。

从返回结果中可以看到,

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

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

l     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]

optParser.print_help()说明:

1、最开始的的MSG_USAGE的值:在这个地方显示出来了。

2、自动添加了-h这个参数。

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

信息就是" filexx[options] arg1 arg2"。

 

 

深入分析

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同样返回空(我就不运行代码了)。

第三种:action="store_false"

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

 

 

参数:default

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

设置些参数是用于返回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',则返回值为,"good luck to you"

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

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

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

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

如果fakeArgs中不存在'-v',则返回值为None

再一次说明了,如果action="store_true"时,verbose的值只与是否'-v'有关。是否也说明了action_true的优先级高于default。

注:action="store_false"的功能与此类似,返回为False或者None。再一次证明了

 

 

参数: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="restore"时对比没使用help参数的'-f'与使用了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]

在action="restore_false"时。

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]")

两个对比的输出结果如下

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]

 

 

参数:type

没有仔细测试,但知道一点时如果type="string"时,将无法使用action="store_false"和action="store_true"。不知是否可以将type理解成verbose的返回值类型。

关于输入的的参数fakeArgs的说明

还是用之前的代码分析

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")

optParser.add_option("-v","--vison", action="store", 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

print args

fakeArgs中的值对于各选项'-v','-f'来说都是前后两个值配对的。

1、正常情况:

结果如下

则options的值为:     {'verbose':'good luck to you', 'fileName': 'file.txt'}

args的值为:           ['arg2', 'arge']

2、不正常情况:

如果连续出现两个选项'-f','-v'。

fakeArgs = ['-f','-v','good luck to you', 'arg2', 'arge']

'-v'作为值传给了fileName。

但verbose返回的是默认值'gggggg',如果没设置将会返回None。换句说话,就是没检测到参数'-v'的存在,这也再一次说明了,fakeArgs中键值配对的观念。前一个数作为选项,后一个作为值。

结果如下:

则options的值为:     {'verbose':'gggggg', 'fileName': '-v'}

args的值为:           ['good luck to you','arg2', 'arge']

3、如果多出一个'x'未被定义则程序会报错。

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

好了,关于optParse这个模块就只学到了这些东西。

python基础之 optparse.OptionParser的更多相关文章

  1. Day11 - Python基础11 模块学习——optparse

    Python 有两个内建的模块用于处理命令行参数: 一个是 getopt,<Deep in python>一书中也有提到,只能简单处理 命令行参数: 另一个是 optparse,它功能强大 ...

  2. Python模块之optparse

    参考: http://www.cnblogs.com/captain_jack/archive/2011/01/11/1933366.html https://docs.python.org/2/li ...

  3. Python基础教程【读书笔记】 - 2016/7/31

    希望通过博客园持续的更新,分享和记录Python基础知识到高级应用的点点滴滴! 第十波:第10章  充电时刻 Python语言的核心非常强大,同时还提供了更多值得一试的工具.Python的标准安装包括 ...

  4. Python 中使用optparse进行参数解析

    使用过Linux/Unix的人都会知道,命令行下的很多命令都需要参数,在C语言中添加和解析参数比较繁琐.Python中提供了optparse模块可以非常方便地处理命令行参数.   1  命令行参数的样 ...

  5. Python参数输入模块-optparse

    废话: 模块名是optparse, 很多人打成optparser.以至于我一直导入导入不了.搞的不知所以. 模块的使用: import optparse #usage 定义的是使用方法,%prog 表 ...

  6. Python模块学习——optparse

    Python 有两个内建的模块用于处理命令行参数: 一个是 getopt,<Deep in python>一书中也有提到,只能简单处理 命令行参数: 另一个是 optparse,它功能强大 ...

  7. python基础31[常用模块介绍]

    python基础31[常用模块介绍]   python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的. 常用的li ...

  8. Python中的optparse模块的使用

    optparse模块主要用来为脚本传递命令参数,采用预先定义好的选项来解析命令行参数. 实例化一个 OptionParser 对象(可以带参,也可以不带参数),带参的话会把参数变量的内容作为帮助信息输 ...

  9. python之最强王者(2)——python基础语法

    背景介绍:由于本人一直做java开发,也是从txt开始写hello,world,使用javac命令编译,一直到使用myeclipse,其中的道理和辛酸都懂(请容许我擦干眼角的泪水),所以对于pytho ...

随机推荐

  1. Josn转DataTable(转)

    使用UI框架开发的时候就常常用到DataTable转Json的情况,但是最近完成一个微信公众号开发的项目,需要把微信接口传过来的json值作为转为DataTable后绑定到服务器控件上. 在网上找了很 ...

  2. oracle索引学习

    查看执行状态: 选中代码直接按F5,或者点击Tools===>>Explain Plan 一.索引的注意事项: 当任何单个查询要检索的行少于或者等于整个表行数的10%时,索引就非常有用.这 ...

  3. Reading source code

    software is a system built up of many parts rebuild that decomposition see the patterns in codes is ...

  4. maven使用笔记一 下载json-lib引发的问题

    一.问题描述(IDEA中): 1,在pom.xml中配置了 <dependency> <groupId>net.sf.json-lib</groupId> < ...

  5. XHTML 结构化:使用 XHTML 重构网站

    http://www.w3school.com.cn/xhtml/xhtml_structural_01.asp 我们曾经为本节撰写的标题是:"XHTML : 简单的规则,容易的方针.&qu ...

  6. css使用技巧

    1) 网站上经常会出现用户输入一大段字符和字母以至于文字无法正常折行,把版式破坏,这样我们就要参考以下样式:word-wrap:break-word; overflow:hidden; 当然必须得有宽 ...

  7. putty设置

    1- 输入要链接的主机地址 2- 设置connection-->SSH-->Tunnels 点击Add 3- 设置connection 修改为30 4- 点击open,出现ssh登陆,输入 ...

  8. [C++程序设计]字符数组的赋值与引用

    只能对字符数组的元素赋值,而不能用赋值语句对整个数组赋值. char c[5]; c={′C′,′h′,′i′,′n′,′a′}; //错误,不能对整个数组一次赋值 c[0]=′C′; c[1]=′h ...

  9. Typecho 代码阅读笔记(三) - 插件机制

    转载请注明出处:http://blog.csdn.net/jh_zzz 以 index.php 为例: /** 初始化组件 */ Typecho_Widget:: widget('Widget_Ini ...

  10. instancetype和id的区别

    一.什么是instancetype instancetype是clang 3.5开始,clang提供的一个关键字,表示某个方法返回的未知类型的Objective-C对象.我们都知道未知类型的的对象可以 ...