python 模块 optparse

optparse,是一个能够让程式设计人员轻松设计出简单明了、易于使用、符合标准的Unix命令列程式的Python模块。生成使用和帮助信息。

下面是一个简单的示例:

import optparse

parser = optparse.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()
print(options)
print(args)

现在你可以输入如下命令测试 :

#显示帮助信息
<yourscript> -h
<yourscript> --help
#测试
<yourscript> --file=outfile -q
<yourscript> -f outfile --quiet
<yourscript> --quiet --file outfile
<yourscript> -q -foutfile
<yourscript> -qfoutfile

你也可以指定 add_option() 方法中 type 参数为其它值,如 int 或者 float 等等:

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

这个选项没有长选项,长选项也是可选的,如果没有指定dest选项,将用命令行的参数名对options对象的值进行存取。store也有其他的两种形式: stort_true 和 store_false, 用于处理带命令行选项后面不带值的情况,例如: -v,-q等命令行参数

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

这样的话,当解析到 '-v' ,options.verbose 将被赋予 True 值,反之,解析到 '-q',会被赋予 False 值。

其它的 actions 值还有 :store_const 、append 、count 、callback

设置 add_option 方法中的 metavar 参数,有助于提醒用户,该命令行参数所期待的参数,如 metavar=“mode”:

parser.add_option("-m", dest="modevar",metavar="mode")

在 help 参数的帮助信息里使用 %default 可以插入该命令行参数的默认值。

如果程序有很多的命令行参数,你可能想为他们进行分组,这时可以使用 OptionGroup
group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk.  "
                    "It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)
原文地址:https://www.cnblogs.com/longxiang92/p/5946862.html