python optparse模組學習

來源:互聯網
上載者:User

標籤:one   html   body   host   its   主程式   imp   div   out   

Python 有兩個內建的模組用於處理命令列參數:

一個是 getopt,getopt只能簡單處理 命令列參數。

另一個是 optparse,是一個能夠讓程式設計人員輕鬆設計出簡單明了、便於使用、符合標準的Unix命令列程式的Python模組。產生使用和協助資訊。

下面是一個簡單的樣本指令碼optparse_exampl_1.py:

[[email protected] python]# vim optparse_exampl_1.py

  #!/usr/bin/env pythonfrom optparse import OptionParserparser = 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

optparse將列印指令碼的選項和協助資訊:

  [[email protected] python]# ./optparse_exampl_1.py -hUsage: optparse_exampl_1.py [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
下面簡單介紹optparse的用法:aptparse 在大多數情況下是相當靈活和強大的,本文介紹常見的optparse用法。首先要匯入OptionParser類,在主程式中要建立一個類:
  from optparse import OptionParser[...]parser = OptionParser()

現在可以定義命令列選項,基本文法是:

  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 組成的列表。瞭解選項操作:action 是 parse_args() 方法的參數之一,它指示 optparse 當解析到一個命令列參數時該如何處理。actions 有一組固定的值可供選擇,預設是’store ‘,表示將命令列參數值儲存在 options 對象裡。
  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 等等:
  parser.add_option("-n", type="int", dest="num")

注意:這個選項沒有長選項,長選項也是可選的,如果沒有指定dest選項,將用命令列的參數名對options對象的值進行存取。store也有其他的兩種形式: stort_true 和 store_false, 用於處理帶命令列選項後面不帶值的情況,例如: -v,-q等命令列參數。

  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 參數用於設定預設值。如:

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

又或者使用set_defaults例如:

  parser.set_defaults(verbose=True)parser.add_option(...)(options, args) = parser.parse_args()
程式產生協助optparse 另一個方便的功能是自動產生程式的協助資訊。你只需要為 add_option() 方法的 help 選項指定協助資訊文本:
  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() 列印程式的協助資訊:

  Usage: <yourscript> [options] arg1 arg2Options:-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=FILEwrite output to FILE-m MODE, --mode=MODE  interaction mode: novice, intermediate, orexpert [default: intermediate]
(注意:當指令碼列印協助資訊後會退出,不會解析其他選項參數)自訂程式使用方法:
  usage = "usage: %prog [options] arg1 arg2"
這行資訊會優先列印在程式的選項資訊前。當中的 %prog,optparse 會以當前程式名的字串來替代:如 os.path.basename.(sys.argv[0])。如果使用者沒有提供自訂的使用方法資訊,optparse 會預設使用: “usage: %prog [options]”。使用者在定義命令列參數的協助資訊時,不用擔心換行帶來的問題,optparse 會處理好這一切。設定 add_option 方法中的 metavar 參數,有助於提醒使用者,該命令列參數所期待的參數,如 metavar=“mode”:
  -m MODE, --mode=MODE
注意: metavar 參數中的字串會自動變為大寫。在 help 參數的協助資訊裡使用 %default 可以插入該命令列參數的預設值。如果程式有很多的命令列參數,你可能想為他們進行分組,這時可以使用 OptionGroup:
  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)

輸出如下:

  Usage: <yourscript> [options] arg1 arg2Options:-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=FILEwrite output to FILE-m MODE, --mode=MODE  interaction mode: novice, intermediate, orexpert [default: intermediate]Dangerous Options:Caution: use these options at your own risk.  It is believed that someof them bite.-g                  Group option.

完整的列子:

  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)group = OptionGroup(parser, "Debug Options")group.add_option("-d", "--debug", action="store_true",help="Print debug information")group.add_option("-s", "--sql", action="store_true",help="Print all SQL statements executed")group.add_option("-e", action="store_true", help="Print every action done")parser.add_option_group(group)

python optparse模組學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.