python模块学习---optparse
来源:互联网 发布:js判断是否等于1 编辑:程序博客网 时间:2024/05/01 18:33
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 组成的列表。
- 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
- Android Bitmap和Drawable
- jquery easyui datagrid 分页
- 192.168.1.1无法登陆无线路由器
- response设置编码
- FPM - Effing Package Management
- python模块学习---optparse
- Kobject Kset
- lua table操作实例详解
- 永久删除的文件怎么恢复
- MFC关闭进程
- 字符串匹配的KMP算法
- 我的Makefile
- Java之笔记 java易混淆概念之类变量、实例变量、局部变量
- Win7下Eclipse中文字体太小