Python中的option Parser

通常來講,Python中有兩個內建的模塊用於處理命令行參數:python

一個是 getopt,《Deep in python》一書中也有提到,只能簡單處理 命令行參數;oracle

另外一個是 optparse,它功能強大,並且易於使用,能夠方便地生成標準的、符合Unix/Posix 規範的命令行說明。app

示例以下:函數

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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是幫助提示ui

最後經過parse_args()函數的解析,得到選項,如options.pdcl的值。
 
下面是一個使用 optparse 的簡單示例:this

1
2
3
4
5
6
7
8
9
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()

如今,你就能夠在命令行下輸入:spa

1
2
3
4
5
<yourscript> - - file = outfile - q
<yourscript> - f outfile - - quiet
<yourscript> - - quiet - - file outfile
<yourscript> - q - foutfile
<yourscript> - qfoutfile

上面這些命令是相同效果的。除此以外, optparse 還爲咱們自動生成命令行的幫助信息:.net

1
2
<yourscript> - h
<yourscript> - - help

輸出:命令行

1
2
3
4
5
6
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 對象:

?
1
2
3
4
5
from optparse import OptionParser
  
[...]
  
parser = OptionParser()

而後,使用 add_option 來定義命令行參數:

1
2
parser.add_option(opt_str, ...,
    attr = value, ...)

每一個命令行參數就是由參數名字符串和參數屬性組成的。如 -f 或者 –file 分別是長短參數名:

1
parser.add_option( "-f" , "--file" , ...)

最後,一旦你已經定義好了全部的命令行參數,調用 parse_args() 來解析程序的命令行:

1
(options, args) = parser.parse_args()

注: 你也能夠傳遞一個命令行參數列表到 parse_args();不然,默認使用 sys.argv[:1]。
parse_args() 返回的兩個值:
① options,它是一個對象(optpars.Values),保存有命令行參數值。只要知道命令行參數名,如 file,就能夠訪問其對應的值: options.file 。
② args,它是一個由 positional arguments 組成的列表。

Actions

action 是 parse_args() 方法的參數之一,它指示 optparse 當解析到一個命令行參數時該如何處理。actions 有一組固定的值可供選擇,默認是'store ',表示將命令行參數值保存在 options 對象裏。

示例代碼以下:

1
2
3
4
5
parser.add_option( "-f" , "--file" ,
    action = "store" , type = "string" , dest = "filename" )
args = [ "-f" , "foo.txt" ]
(options, args) = parser.parse_args(args)
print options.filename

最後將會打印出 「foo.txt」。

當 optparse 解析到'-f',會繼續解析後面的'foo.txt',而後將'foo.txt'保存到 options.filename 裏。當調用 parser.args() 後,options.filename 的值就爲'foo.txt'。
你也能夠指定 add_option() 方法中 type 參數爲其它值,如 int 或者 float 等等:

1
parser.add_option( "-n" , type = "int" , dest = "num" )

默認地,type 爲'string'。也正如上面所示,長參數名也是可選的。其實,dest 參數也是可選的。若是沒有指定 dest 參數,將用命令行的參數名來對 options 對象的值進行存取。
store 也有其它的兩種形式: store_true 和 store_false ,用於處理帶命令行參數後面不 帶值的狀況。如 -v,-q 等命令行參數:

1
2
parser.add_option( "-v" , action = "store_true" , dest = "verbose" )
parser.add_option( "-q" , action = "store_false" , dest = "verbose" )

這樣的話,當解析到 '-v',options.verbose 將被賦予 True 值,反之,解析到 '-q',會被賦予 False 值。
其它的 actions 值還有:
store_const 、append 、count 、callback 。

默認值

parse_args() 方法提供了一個 default 參數用於設置默認值。如:

1
2
parser.add_option( "-f" , "--file" , action = "store" , dest = "filename" , default = "foo.txt" )
parser.add_option( "-v" , action = "store_true" , dest = "verbose" , default = True )

又或者使用 set_defaults():

1
2
3
parser.set_defaults(filename = "foo.txt" ,verbose = True )
parser.add_option(...)
(options, args) = parser.parse_args()

生成程序幫助

optparse 另外一個方便的功能是自動生成程序的幫助信息。你只須要爲 add_option() 方法的 help 參數指定幫助信息文本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage = usage)
parser.add_option( "-v" , "--verbose" ,
    action = "store_true" , dest = "verbose" , default = True ,
    help = "make lots of noise [default]" )
parser.add_option( "-q" , "--quiet" ,
    action = "store_false" , dest = "verbose" ,
    help = "be vewwy quiet (I'm hunting wabbits)" )
parser.add_option( "-f" , "--filename" ,
    metavar = "FILE" , help = "write output to FILE" ),
parser.add_option( "-m" , "--mode" ,
    default = "intermediate" ,
   help = "interaction mode: novice, intermediate, "
    "or expert [default: %default]" )

當 optparse 解析到 -h 或者 –help 命令行參數時,會調用 parser.print_help() 打印程序的幫助信息:

1
2
3
4
5
6
7
8
9
10
usage: <yourscript> [options] arg1 arg2
  
options:
  - h, - - help  show this help message and exit
  - v, - - verbose  make lots of noise [default]
  - q, - - quiet  be vewwy quiet (I'm hunting wabbits)
  - f FILE , - - filename = FILE
    write output to FILE
  - m MODE, - - mode = MODE interaction mode: novice, intermediate, or
    expert [default: intermediate]

注意: 打印出幫助信息後,optparse 將會退出,再也不解析其它的命令行參數。
以上面的例子來一步步解釋如何生成幫助信息:

① 自定義的程序使用方法信息(usage message):
 
usage = "usage: %prog [options] arg1 arg2" 
這行信息會優先打印在程序的選項信息前。當中的 %prog,optparse 會以當前程序名的字符串來替代:如 os.path.basename.(sys.argv[0])。
若是用戶沒有提供自定義的使用方法信息,optparse 會默認使用: 「usage: %prog [options]」。
② 用戶在定義命令行參數的幫助信息時,不用擔憂換行帶來的問題,optparse 會處理好這一切。
③ 設置 add_option 方法中的 metavar 參數,有助於提醒用戶,該命令行參數所期待的參數,如 metavar=「mode」:

1
- m MODE, - - mode = MODE

注意: metavar 參數中的字符串會自動變爲大寫。
④ 在 help 參數的幫助信息裏使用 %default 能夠插入該命令行參數的默認值。

若是程序有不少的命令行參數,你可能想爲他們進行分組,這時可使用 OptonGroup:

1
2
3
4
5
group = OptionGroup(parser, ``Dangerous Options'',
    ``Caution: use these options at your own risk. ``
    ``It is believed that some of them bite.'')
group.add_option(`` - g' ', action=' 'store_true' ', help=' 'Group option.' ')
parser.add_option_group(group)

下面是將會打印出來的幫助信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
usage: [options] arg1 arg2
  
options:
  - h, - - help  show this help message and exit
  - v, - - verbose make lots of noise [default]
  - q, - - quiet  be vewwy quiet (I'm hunting wabbits)
  - fFILE, - - file = FILE write output to FILE
  - mMODE, - - mode = MODE interaction mode: one of 'novice' , 'intermediate'
    [default], 'expert'
  
  Dangerous Options:
  Caution: use of these options is at your own risk. It is believed that
  some of them bite.
  - g   Group option.

顯示程序版本

象 usage message 同樣,你能夠在建立 OptionParser 對象時,指定其 version 參數,用於顯示當前程序的版本信息:

1
parser = OptionParser(usage = "%prog [-f] [-q]" , version = "%prog 1.0" )

 
這樣,optparse 就會自動解釋 –version 命令行參數:

1
2
$ / usr / bin / foo - - version
foo 1.0

處理異常

包括程序異常和用戶異常。這裏主要討論的是用戶異常,是指因用戶輸入無效的、不完整的命令行參數而引起的異常。optparse 能夠自動探測並處理一些用戶異常:

1
2
3
4
5
6
7
8
9
$ / usr / bin / foo - n 4x
usage: foo [options]
  
foo: error: option - n: invalid integer value: '4x'
  
$ / usr / bin / foo - n
usage: foo [options]
  
foo: error: - n option requires an argument

用戶也可使用 parser.error() 方法來自定義部分異常的處理:

1
2
3
4
(options, args) = parser.parse_args()
[...]
if options.a and options.b:
  parser.error( "options -a and -b are mutually exclusive" )

上面的例子,當 -b 和 -b 命令行參數同時存在時,會打印出「options -a and -b are mutually exclusive「,以警告用戶。
若是以上的異常處理方法還不能知足要求,你可能須要繼承 OptionParser 類,並重載 exit() 和 erro() 方法。

完整的程序例子以下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from optparse import OptionParser
[...]
def main():
  usage = "usage: %prog [options] arg"
  parser = OptionParser(usage)
  parser.add_option( "-f" , "--file" , dest = "filename" ,
    help = "read data from FILENAME" )
  parser.add_option( "-v" , "--verbose" ,
    action = "store_true" , dest = "verbose" )
  parser.add_option( "-q" , "--quiet" ,
    action = "store_false" , dest = "verbose" )
  [...]
  (options, args) = parser.parse_args()
  if len (args) ! = 1 :
  parser.error( "incorrect number of arguments" )
  if options.verbose:
  print "reading %s..." % options.filename
  [...]
  
if __name__ = = "__main__" :
  main()

相信本文所述對你們的Python程序設計有必定的借鑑價值。

相關文章
相關標籤/搜索