python模块学习---optparse
2013-12-09 15:03
429 查看
Python 有两个内建的模块用于处理命令行参数:
一个是 getopt,《Deep in python》一书中也有提到,只能简单处理 命令行参数;另一个是 optparse,它功能强大,而且易于使用,可以方便地生成标准的、符合Unix/Posix 规范的命令行说明。
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()
现在,妳就可以在命令行下输入:
<yourscript> --file=outfile -q <yourscript> -f outfile --quiet <yourscript> --quiet --file outfile <yourscript> -q -foutfile <yourscript> -qfoutfile
上面这些命令是相同效果的。除此之外, optparse 还为我们自动生成命令行的帮助信息:
<yourscript> -h <yourscript> --help
输出:
usage: <yourscript> [options] options: -h, --help show this help message and exit -f FILE, --file=FILE write report to FILE -q, --quiet don't print status messages to stdout
简单流程:
首先,必须 import OptionParser 类,创建一个 OptionParser 对象:from optparse import OptionParser [...] parser = OptionParser()
然后,使用 add_option 来定义命令行参数:
parser.add_option(opt_str, ..., attr=value, ...)
每个命令行参数就是由参数名字符串和参数属性组成的。如 -f 或者 –file 分别是长短参数名:
parser.add_option("-f", "--file", ...)
最后,一旦你已经定义好了所有的命令行参数,调用 parse_args() 来解析程序的命令行:
(options, args) = parser.parse_args()
注: 你也可以传递一个命令行参数列表到 parse_args();否则,默认使用 sys.argv[:1]。
parse_args() 返回的两个值:
options,它是一个对象(optpars.Values),保存有命令行参数值。只要知道命令行参数名,如 file,就可以访问其对应的值: options.file 。
args,它是一个由 positional arguments 组成的列表。
详细参考:http://www.cnblogs.com/captain_jack/archive/2011/01/11/1933366.html
相关文章推荐
- 我的python学习之路---命行选项模块optparse
- Python模块学习——optparse
- 转载---Python模块学习optparse 处理命令行参数
- Python模块学习——optparse (详细)
- Python模块学习——optparse
- Python模块学习——optparse
- Python模块学习——optparse
- Python模块学习——optparse
- Python模块学习——optparse
- Python模块学习——optparse
- Python模块学习——optparse
- Python模块学习——optparse
- Python中optparse模块使用学习
- Python模块学习——optparse
- Python模块学习——optparse
- Python模块学习——optparse
- Python模块学习——optparse
- Python模块学习——optparse
- Python模块学习——optparse