optparse模块

来源:互联网 发布:php页面跳转url不变 编辑:程序博客网 时间:2024/05/19 09:13

       该模块提供了解析命令行选项的接口,其中optparse已经在2.7以后的版本中已经不再继续开发好此模块,从2.7后,将开发argparse模块。

optparse模块使用的代码示例:

#!/bin/sh##  This is a learning notes in the process of analysing repo python scripts#   authour: fuyajun1983cn@hotmail.com#magic='--calling-python-from-/bin/sh--'"""exec" python -E "$0" "$@" """#$magic"if __name__ == '__main__':  import sys  if sys.argv[-1] == '#%s' % magic:    del sys.argv[-1]del magic#print "An example of using optparse\n"from optparse import OptionParserparser = OptionParser()parser.add_option("-f", "--file", dest="filename",                  help="write report to FILE", metavar="FILE")parser.add_option("-q", "--quiet",                  action="store_false", dest="verbose", default=True,                  help="don't print status messages to stdout")(options, args) = parser.parse_args()#the default argument list is sys.argv[1:]

其中,options表示指定的选项,args表示对应的位置参数

理解optionactions

Actions告诉optparse怎样处理命令行对应的选项,这些Actions已经预先定义在optparse模块当中,当然可以扩展出更多的Action。默认情况下,actionstore

StoreAction

optparse将紧随其后的参数保存在DEST指定的变量中。如:

parser.add_option("-f", "--file",                  action="store", type="string", dest="filename")

执行如下语句后:

args = ["-f", "foo.txt"](options, args) = parser.parse_args(args)

options.filename的值为foo.txt

optparse也支持其他类型的参数,如:

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

对于布尔类型的选项,有两个特别的actionstore_truestore_false

如:

parser.add_option("-v", action="store_true", dest="verbose")parser.add_option("-q", action="store_false", dest="verbose")

上述代码表示:当选项为-v时,verboseTrue,当选项为-q时,verboseFalse

其他的一些Actions

"store_const"
存储一个常量
"append"
将该选项的参数追加到一个列表中
"count"
将某个计数器加1
"callback"
调用某个特定的函数

默认值

parser.add_option("-v", action="store_true", dest="verbose", default=False)parser.add_option("-q", action="store_false", dest="verbose", default=True)

首先,默认值与选项无关,只与dest值关联,当多次设置默认值时,最后一次设置的默认值有效。


产生帮助信息

parser.add_option("-v", "--verbose",                  action="store_true", dest="verbose", default=True,                  help="make lots of noise [default]")

metavar

它表示用户需要提供的参数,默认情况下,optparsedest变量名全部转为大写作为metavar的值,当然,我们也可以显示的指定metavar的值。

分组选项

# Logginggroup = init_optparse.add_option_group('Logging options')group.add_option('-q', '--quiet',                 dest="quiet", action="store_true", default=False,                 help="be quiet"),# Manifestgroup = init_optparse.add_option_group('Manifest options')group.add_option('-u', '--manifest-url',                 dest='manifest_url',                 help='manifest repository location', metavar='URL')