时间:2021-07-01 10:21:17 帮助过:51人阅读
代码如下:
from optparse import OptionParser
[...]
def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-f", "--file", dest="filename",
help="read data from FILENAME")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose")
[...]
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
if options.verbose:
print "reading %s..." % options.filename
[...]
if __name__ == "__main__":
main()
代码如下:
OptionParser.add_option(option)
OptionParser.add_option(*opt_str, attr=value, ...)
代码如下:
parser.add_option(“-f”, attr=value, …)
代码如下:
parser.add_option(“–foo”, attr=value, …)
代码如下:
parser.add_option("-f", "--file", action="store", type="string", dest="filename")
代码如下:
-ffoo
-f foo
--file=foo
--file foo
代码如下:
options.filename = “foo”
代码如下:
(options, args) = parser.parse_args()
行为(action)
●store 默认行为,保存值到dest
●“store_const” 保存常量
●“append” append this option's argument to a list
●“count” increment a counter by one
●“callback” call a specified function
设置默认值(default)
代码如下:
parser.add_option("-v", action="store_true", dest="verbose", default=True)
parser.set_defaults(verbose=True)
提供help选项即可,可以用parser.print_help()打印出来
代码如下:
parser.add_option(“-f”, “–file”, dest=”filename”,help=”write report to FILE”, metavar=”FILE”)
支持store_true和store_false两个行为
代码如下:
parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose")
错误处理
代码如下:
(options, args) = parser.parse_args()
[...]
if options.a and options.b:
parser.error("options -a and -b are mutually exclusive")
格式如下
class optparse.OptionGroup(parser, title, description=None)
代码如下:
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)
代码如下:
Usage:
Options:
-h, --help show this help message and exit
-v, --verbose make lots of noise [default]
-q, --quiet be vewwy quiet (I'm hunting wabbits)
-f FILE, --filename=FILE
write output to FILE
-m MODE, --mode=MODE interaction mode: novice, intermediate, or
expert [default: intermediate]
Dangerous Options:
Caution: use these options at your own risk. It is believed that some
of them bite.
-g Group option.