jekeyhui99 发表于 2019-1-16 19:16:11

Python模块: 命令行解析optionparser

<p>Python 有两个内建的模块用于处理命令行参数:</p><p>一个是 getopt,《Deep in python》一书中也有提到,只能简单处理 命令行参数;</p><p>另一个是 optparse,它功能强大,而且易于使用,可以方便地生成标准的、符合Unix/Posix 规范的命令行说明。</p><p><br></p><p>使用optionparser模块来解析</p><p><br></p><p>optionparser的执行过程:</p><p><br></p><p>导入optionparser : from optparse import OptionParser</p><p>构造optionparser的对象:parser = OptionParser()</p><p>往optionparser对象中增加option :parser.add_option()</p><p><br></p><p>调用optionparser的解析函数:(options, args) = parser.parse_args()</p><p>在options中使用解析到的options,在args中使用其他的args。</p><p><br></p><p>&nbsp;</p><p><br></p><p>&nbsp;</p><p><br></p><p>&nbsp;</p><p><br></p><p>1. 普通的格式(-a a -b b ...)</p><p><br></p><p>&nbsp;1 #parse command</p><p>&nbsp;2&nbsp; &nbsp; &nbsp;usage = "usage: python %prog "</p><p>&nbsp;3&nbsp; &nbsp; &nbsp;parser = OptionParser(usage=usage)</p><p>&nbsp;4&nbsp; &nbsp; &nbsp;parser.add_option('-d', '--device', help="Device serial number.")</p><p>&nbsp;5&nbsp; &nbsp; &nbsp;parser.add_option('-o', '--osVersion', help="Os version.")</p><p>&nbsp;6&nbsp; &nbsp; &nbsp;options, args = parser.parse_args(sys.argv)</p><p>&nbsp;7&nbsp; &nbsp; &nbsp;</p><p>&nbsp;8&nbsp; &nbsp; &nbsp;if options.device is None:</p><p>&nbsp;9&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;......</p><p>10&nbsp; &nbsp; &nbsp;else:</p><p>11&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;......</p><p>12&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</p><p>13&nbsp; &nbsp; &nbsp;if options.osVersion is None:</p><p>14&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;osVersion = ......</p><p>15&nbsp; &nbsp; &nbsp;elif options.osVersion is "1":</p><p>16&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;osVersion = ......</p><p>17&nbsp; &nbsp; &nbsp;else:</p><p>18&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print "Error"</p><p>19&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sys.exit(-1)</p><p>2. 只需要参数,不需要参数内容的格式(-a --bb ...)</p><p><br></p><p>&nbsp;</p><p><br></p><p>parser.add_option('--nl', action="store_false", help="No Need.")</p><p>&nbsp;</p><p><br></p><p>3. 直接调用方法的格式,不需要参数内容</p><p><br></p><p>&nbsp;</p><p><br></p><p>parser.add_option("-l", "--list", action="callback", callback=test_list, help="check the list.")</p><p>&nbsp;</p><p><br></p><p>4. 直接调用方法,并传参数的格式</p><p><br></p><p>&nbsp;</p><p><br></p><p>parser.add_option("-u", "--upload", action="callback", callback=test_upload, callback_args=(ingredient,build), help="upload result.")</p><p>&nbsp;</p><p><br></p><p>&nbsp;</p><p><br></p><p>&nbsp;</p><p><br></p><p>&nbsp;</p><p><br></p><p>&nbsp;</p><p><br></p><p>&nbsp;</p><p><br></p><p>示例</p><p>下面是一个使用 optparse 的简单示例:</p><p><br></p><p>Python代码&nbsp;</p><p>from optparse import OptionParser&nbsp;&nbsp;</p><p>[...]&nbsp;&nbsp;</p><p>parser = OptionParser()&nbsp;&nbsp;</p><p>parser.add_option("-f", "--file", dest="filename",&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; help="write report to FILE", metavar="FILE")&nbsp;&nbsp;</p><p>parser.add_option("-q", "--quiet",&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; action="store_false", dest="verbose", default=True,&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; help="don't print status messages to stdout")&nbsp;&nbsp;</p><p>&nbsp;&nbsp;</p><p>(options, args) = parser.parse_args()&nbsp;&nbsp;</p><p>&nbsp;</p><p>现在,妳就可以在命令行下输入:</p><p><br></p><p>Python代码&nbsp;</p><p>&lt;yourscript&gt; --file=outfile -q&nbsp;&nbsp;</p><p>&lt;yourscript&gt; -f outfile --quiet&nbsp;&nbsp;</p><p>&lt;yourscript&gt; --quiet --file outfile&nbsp;&nbsp;</p><p>&lt;yourscript&gt; -q -foutfile&nbsp;&nbsp;</p><p>&lt;yourscript&gt; -qfoutfile&nbsp;&nbsp;</p><p>&nbsp;</p><p>上面这些命令是相同效果的。除此之外, optparse 还为我们自动生成命令行的帮助信息:</p><p><br></p><p>Python代码&nbsp;</p><p>&lt;yourscript&gt; -h&nbsp;&nbsp;</p><p>&lt;yourscript&gt; --help&nbsp;&nbsp;</p><p>&nbsp;</p><p>输出:</p><p><br></p><p>Python代码&nbsp;</p><p>usage: &lt;yourscript&gt; &nbsp;&nbsp;</p><p>&nbsp;&nbsp;</p><p>options:&nbsp;&nbsp;</p><p>&nbsp; -h, --help&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; show this help message and exit&nbsp;&nbsp;</p><p>&nbsp; -f FILE, --file=FILE&nbsp; write report to FILE&nbsp;&nbsp;</p><p>&nbsp; -q, --quiet&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;don't print status messages to stdout&nbsp;&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p><br></p><p>简单流程</p><p>首先,必须 import OptionParser 类,创建一个 OptionParser 对象:</p><p><br></p><p>Python代码&nbsp;</p><p>from optparse import OptionParser&nbsp;&nbsp;</p><p>&nbsp;&nbsp;</p><p>[...]&nbsp;&nbsp;</p><p>&nbsp;&nbsp;</p><p>parser = OptionParser()&nbsp;&nbsp;</p><p>&nbsp;</p><p>然后,使用 add_option 来定义命令行参数:</p><p><br></p><p>Python代码&nbsp;</p><p>parser.add_option(opt_str, ...,&nbsp;&nbsp;</p><p>&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; attr=value, ...)&nbsp;&nbsp;</p><p>&nbsp;</p><p>每个命令行参数就是由参数名字符串和参数属性组成的。如 -f 或者 –file 分别是长短参数名:</p><p><br></p><p>Python代码&nbsp;</p><p>parser.add_option("-f", "--file", ...)&nbsp;&nbsp;</p><p>&nbsp;</p><p>最后,一旦你已经定义好了所有的命令行参数,调用 parse_args() 来解析程序的命令行:</p><p><br></p><p>Python代码&nbsp;</p><p>(options, args) = parser.parse_args()&nbsp;&nbsp;</p><p>&nbsp;</p><p>注: 你也可以传递一个命令行参数列表到 parse_args();否则,默认使用 sys.argv[:1]。</p><p><br></p><p>parse_args() 返回的两个值:</p><p><br></p><p>options,它是一个对象(optpars.Values),保存有命令行参数值。只要知道命令行参数名,如 file,就可以访问其对应的值: options.file 。</p><p>args,它是一个由 positional arguments 组成的列表。</p><p>Actions</p><p>action 是 parse_args() 方法的参数之一,它指示 optparse 当解析到一个命令行参数时该如何处理。actions 有一组固定的值可供选择,默认是’store ‘,表示将命令行参数值保存在 options 对象里。</p><p><br></p><p>示例</p><p><br></p><p>Python代码&nbsp;</p><p>parser.add_option("-f", "--file",&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; action="store", type="string", dest="filename")&nbsp;&nbsp;</p><p>args = ["-f", "foo.txt"]&nbsp;&nbsp;</p><p>(options, args) = parser.parse_args(args)&nbsp;&nbsp;</p><p>print options.filename&nbsp;&nbsp;</p><p>&nbsp;</p><p>最后将会打印出 “foo.txt”。</p><p><br></p><p>当 optparse 解析到’-f’,会继续解析后面的’foo.txt’,然后将’foo.txt’保存到 options.filename 里。当调用 parser.args() 后,options.filename 的值就为’foo.txt’。</p><p><br></p><p>你也可以指定 add_option() 方法中 type 参数为其它值,如 int 或者 float 等等:</p><p><br></p><p>Python代码&nbsp;</p><p>parser.add_option("-n", type="int", dest="num")&nbsp;&nbsp;</p><p>&nbsp;</p><p>默认地,type 为’string’。也正如上面所示,长参数名也是可选的。其实,dest 参数也是可选的。如果没有指定 dest 参数,将用命令行的参数名来对 options 对象的值进行存取。</p><p><br></p><p>store 也有其它的两种形式: store_true 和 store_false ,用于处理带命令行参数后面不 带值的情况。如 -v,-q 等命令行参数:</p><p><br></p><p>Python代码&nbsp;</p><p>parser.add_option("-v", action="store_true", dest="verbose")&nbsp;&nbsp;</p><p>parser.add_option("-q", action="store_false", dest="verbose")&nbsp;&nbsp;</p><p>&nbsp;</p><p>这样的话,当解析到 ‘-v’,options.verbose 将被赋予 True 值,反之,解析到 ‘-q’,会被赋予 False 值。</p><p><br></p><p>其它的 actions 值还有:</p><p><br></p><p>store_const 、append 、count 、callback 。</p><p><br></p><p>&nbsp;</p><p><br></p><p>默认值</p><p>parse_args() 方法提供了一个 default 参数用于设置默认值。如:</p><p><br></p><p>Python代码&nbsp;</p><p>parser.add_option("-f","--file", action="store", dest="filename", default="foo.txt")&nbsp;&nbsp;</p><p>parser.add_option("-v", action="store_true", dest="verbose", default=True)&nbsp;&nbsp;</p><p>&nbsp;</p><p>又或者使用 set_defaults():</p><p><br></p><p>Python代码&nbsp;</p><p>parser.set_defaults(filename="foo.txt",verbose=True)&nbsp;&nbsp;</p><p>parser.add_option(...)&nbsp;&nbsp;</p><p>(options, args) = parser.parse_args()&nbsp;&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p><br></p><p>生成程序帮助</p><p>optparse 另一个方便的功能是自动生成程序的帮助信息。你只需要为 add_option() 方法的 help 参数指定帮助信息文本:</p><p><br></p><p>Python代码&nbsp;</p><p>usage = "usage: %prog arg1 arg2"&nbsp;&nbsp;</p><p>parser = OptionParser(usage=usage)&nbsp;&nbsp;</p><p>parser.add_option("-v", "--verbose",&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; action="store_true", dest="verbose", default=True,&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; help="make lots of noise ")&nbsp;&nbsp;</p><p>parser.add_option("-q", "--quiet",&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; action="store_false", dest="verbose",&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; help="be vewwy quiet (I'm hunting wabbits)")&nbsp;&nbsp;</p><p>parser.add_option("-f", "--filename",&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; metavar="FILE", help="write output to FILE"),&nbsp;&nbsp;</p><p>parser.add_option("-m", "--mode",&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; default="intermediate",&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; help="interaction mode: novice, intermediate, "&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"or expert ")&nbsp;&nbsp;</p><p>&nbsp;</p><p>当 optparse 解析到 -h 或者 –help 命令行参数时,会调用 parser.print_help() 打印程序的帮助信息:</p><p><br></p><p>Python代码&nbsp;</p><p>usage: &lt;yourscript&gt; arg1 arg2&nbsp;&nbsp;</p><p>&nbsp;&nbsp;</p><p>options:&nbsp;&nbsp;</p><p>&nbsp; -h, --help&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; show this help message and exit&nbsp;&nbsp;</p><p>&nbsp; -v, --verbose&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;make lots of noise &nbsp;&nbsp;</p><p>&nbsp; -q, --quiet&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;be vewwy quiet (I'm hunting wabbits)&nbsp;&nbsp;</p><p>&nbsp; -f FILE, --filename=FILE&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; write output to FILE&nbsp;&nbsp;</p><p>&nbsp; -m MODE, --mode=MODE&nbsp; interaction mode: novice, intermediate, or&nbsp;&nbsp;</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; expert &nbsp;&nbsp;</p><p>&nbsp;</p><p>注意: 打印出帮助信息后,optparse 将会退出,不再解析其它的命令行参数。</p><p>---------------------&nbsp;</p><p>作者:曾先森向前进&nbsp;</p><p>来源:CSDN&nbsp;</p><p>原文:https://blog.csdn.net/zwqjoy/article/details/78812855&nbsp;</p><p></p>
页: [1]
查看完整版本: Python模块: 命令行解析optionparser