Python中optionParser模块的使用方法实例教程

2019-10-05 21:17:31于海丽

本文以实例形式较为详尽的讲述了Python中optionParser模块的使用方法,对于深入学习Python有很好的借鉴价值。之用。具体分析如下:

一般来说,Python中有两个内建的模块用于处理命令行参数:

一个是 getopt,《Deep in python》一书中也有提到,只能简单处理 命令行参数;

另一个是 optparse,它功能强大,而且易于使用,可以方便地生成标准的、符合Unix/Posix 规范的命令行说明。

示例如下:

from optparse import OptionParser 
parser = OptionParser() 
parser.add_option("-p", "--pdbk", action="store_true", 
   dest="pdcl", 
   default=False, 
   help="write pdbk data to oracle db") 
parser.add_option("-z", "--zdbk", action="store_true", 
   dest="zdcl", 
   default=False, 
   help="write zdbk data to oracle db") 
(options, args) = parser.parse_args() 
if options.pdcl==True: 
 print 'pdcl is true' 
if options.zdcl==True: 
 print 'zdcl is true' 

add_option用来加入选项,action是有store,store_true,store_false等,dest是存储的变量,default是缺省值,help是帮助提示

最后通过parse_args()函数的解析,获得选项,如options.pdcl的值。
 
下面是一个使用 optparse 的简单示例:

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", ...)