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

转载于:https://www.cnblogs.com/mcznhaha/p/4815437.html

转载:optparse模块OptionParser学习相关推荐

  1. 【转】Python之optparse模块OptionParser的使用方法

    一.基本用法 optparse,是一个更够让程序设计人员轻松设计出简单明了.易于使用.符合标准的Unix命令例程式的Python模块.生成使用和帮助信息 首先你必须导入该类,并创建一个OptionPa ...

  2. Python [9] optparse模块生成命令行帮助信息

    起初,最先接触python命令行传参是sys模块的argv方法,此方法功能简单,稍微增加一些需求,就不难满足需要了 那么今天就和大家聊聊optparse模块来替换sys模块的argv方法 一.optp ...

  3. optparse模块

    该模块提供了解析命令行选项的接口,其中optparse已经在2.7以后的版本中已经不再继续开发好此模块,从2.7后,将开发argparse模块. optparse模块使用的代码示例: #!/bin/s ...

  4. Python中的 optparse模块

    python的内置模块中对于命令行的解析模块共两个getopt 和 optparse .不过getopt过于简单,往往不能满足需求.此时可以使用optparse模块.这个模块相对于getopt更新,功 ...

  5. Python下使用optparse模块实现对多个文件进行统计【二】

    一个取代shell wc -l 命令的python小脚本 1.通过python下optparse模块下OptionParser类是新对文件的统计 #!/opt/data/ipy/bin/python ...

  6. python getopt argparse_python OptParse模块和argparse命令行解析的用法详解

    https://www.cnblogs.com/wj-1314/p/8974021.html OptParse模块的简单介绍 Python 有两个内建的模块用于处理命令行参数: 一个是 getopt只 ...

  7. python中parse是什么_Python中optparse模块使用浅析

    最近遇到一个问题,是指定参数来运行某个特定的进程,这很类似Linux中一些命令的参数了,比如ls -a,为什么加上-a选项会响应.optparse模块实现的也是类似的功能,它是为脚本传递命令参数. 使 ...

  8. python 获取参数模块_Python中获取启动程序时后面跟的参数的方法(optparse模块)【冰斌棒】...

    Python中获取启动程序时后面跟的参数的方法(optparse模块)[冰斌棒] 3年前 (2018-01-29)    作者:冰斌棒    分类:冰斌棒18程序计划    阅读次数:871 评论(0 ...

  9. python hank_python optparse模块

    optparse是专门用来在命令行添加选项的一个模块. 首先来看一段示例代码 from optparse import OptionParser MSG_USAGE = "myprog[ - ...

最新文章

  1. TabLayout 在宽屏幕上tab不能平均分配的问题解决
  2. Scrapy框架中管道的使用
  3. php 上传文件名乱码,php上传文件时文件名乱码怎么办
  4. pandas数据预处理(字段筛选、query函数进行数据筛选、缺失值删除)、seaborn可视化分面图(facet)、seaborn使用Catplot可视化分面箱图(Faceted Boxplot)
  5. 张亚勤清华AIR战队首次亮相,这阵容不是一般强
  6. mongodb 分组聚合_MongoDB按键值对进行聚合/分组
  7. 5道Python函数练习
  8. OBS Windows10 1909版本黑屏问题解决方案
  9. 演示使用Metasploit入侵Windows
  10. OpenCV4图像处理算子不完全手册-应用篇
  11. Excel如何给单元格添加下拉选项?实用小技巧!怎样给单元格加入下拉列表?
  12. 1w存银行一年多少利息_在银行存定期一万块一年有多少利息?
  13. 如何配置谷歌浏览器_如何科学地使用Chrome?下载谷歌浏览器?
  14. MySql基本查询、连接查询、子查询、正则表达查询讲解
  15. BlackBerry 9850 应用:新浪微博
  16. WWW网上下载管理器
  17. dstwo linux n64,纳尼?论坛惊现NDS用的N64模拟器正在开发?
  18. 不同场景下的授信额度模型分析
  19. 部署项目到云服务器上所遇到的困难
  20. 用QEMU搭建arm开发环境之三:编译BusyBox建立最简单的文件系统

热门文章

  1. 谷歌Android笔记本,运行安卓+Chrome OS合体新系统:谷歌Pixel 3笔记本被曝光
  2. 【已失效】免翻在Chrome上使用新必应(New Bing)聊天机器人
  3. 用Python删除含有特定字符串的行
  4. 前后端不分离,分页器组件(python-dango)
  5. 律师向公安部举报称微软黑屏是最大黑客行为
  6. 微信小程序获取用户收货地址与指纹验证接口(安卓和iphone)
  7. mysql java配置文件_Mysql配置文件参数优化
  8. 【图文并茂】手把手教你重装Win10系统
  9. Navicat Premium 15 for Mac(数据库管理)
  10. 围绕开源的系列思考之二——企业篇