代码改变世界

python OptionParser模块

2013-06-26 17:19  youxin  阅读(467)  评论(0编辑  收藏  举报

Python中强大的选项处理模块。

 

#!/usr/bin/python

from optparse import OptionParser

parser = 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.filename,options.verbose

将上面代码保存到文件option1.py(名字随便),添加执行权限并运行:

./option1.py
./option1.py -f
./option1.py -f foo.txt
./option1.py -f foo.txt -q
./option1.py -qffoo.txt # 注意这个和下面对比
./option1.py -fqfoo.txt
./option1.py --file foo.txt
./option1.py --quiet
./option1.py -h   # -h和--help默认情况optpars自动处理。
./option1.py --help

参考:http://www.cnblogs.com/captain_jack/archive/2011/01/11/1933366.html

http://jianlee.ylinux.org/Computer/Python/OptionParser.html

在2.7版本中已经废弃了,新的argparse替代。

Deprecated since version 2.7: The optparse module is deprecated and will not be developed further; development will continue with theargparse module.