欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中optionParser模塊的使用方法實(shí)例教程

 更新時(shí)間:2014年08月29日 10:01:17   投稿:shichen2014  
這篇文章主要介紹了Python中optionParser模塊的使用方法,功能非常強(qiáng)大,需要的朋友可以參考下

本文以實(shí)例形式較為詳盡的講述了Python中optionParser模塊的使用方法,對(duì)于深入學(xué)習(xí)Python有很好的借鑒價(jià)值。分享給大家供大家參考之用。具體分析如下:

一般來(lái)說(shuō),Python中有兩個(gè)內(nèi)建的模塊用于處理命令行參數(shù):

一個(gè)是 getopt,《Deep in python》一書(shū)中也有提到,只能簡(jiǎn)單處理 命令行參數(shù);

另一個(gè)是 optparse,它功能強(qiáng)大,而且易于使用,可以方便地生成標(biāo)準(zhǔn)的、符合Unix/Posix 規(guī)范的命令行說(shuō)明。

示例如下:

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用來(lái)加入選項(xiàng),action是有store,store_true,store_false等,dest是存儲(chǔ)的變量,default是缺省值,help是幫助提示

最后通過(guò)parse_args()函數(shù)的解析,獲得選項(xiàng),如options.pdcl的值。
 
下面是一個(gè)使用 optparse 的簡(jiǎn)單示例:

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() 

現(xiàn)在,你就可以在命令行下輸入:

<yourscript> --file=outfile -q 
<yourscript> -f outfile --quiet 
<yourscript> --quiet --file outfile 
<yourscript> -q -foutfile 
<yourscript> -qfoutfile 

上面這些命令是相同效果的。除此之外, optparse 還為我們自動(dòng)生成命令行的幫助信息:

<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 

簡(jiǎn)單流程

首先,必須 import OptionParser 類(lèi),創(chuàng)建一個(gè) OptionParser 對(duì)象:

from optparse import OptionParser 
 
[...] 
 
parser = OptionParser()

然后,使用 add_option 來(lái)定義命令行參數(shù):

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

每個(gè)命令行參數(shù)就是由參數(shù)名字符串和參數(shù)屬性組成的。如 -f 或者 –file 分別是長(zhǎng)短參數(shù)名:

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

最后,一旦你已經(jīng)定義好了所有的命令行參數(shù),調(diào)用 parse_args() 來(lái)解析程序的命令行:

(options, args) = parser.parse_args()

注: 你也可以傳遞一個(gè)命令行參數(shù)列表到 parse_args();否則,默認(rèn)使用 sys.argv[:1]。
parse_args() 返回的兩個(gè)值:
① options,它是一個(gè)對(duì)象(optpars.Values),保存有命令行參數(shù)值。只要知道命令行參數(shù)名,如 file,就可以訪問(wèn)其對(duì)應(yīng)的值: options.file 。
② args,它是一個(gè)由 positional arguments 組成的列表。

Actions

action 是 parse_args() 方法的參數(shù)之一,它指示 optparse 當(dāng)解析到一個(gè)命令行參數(shù)時(shí)該如何處理。actions 有一組固定的值可供選擇,默認(rèn)是'store ',表示將命令行參數(shù)值保存在 options 對(duì)象里。

示例代碼如下:

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

最后將會(huì)打印出 “foo.txt”。

當(dāng) optparse 解析到'-f',會(huì)繼續(xù)解析后面的'foo.txt',然后將'foo.txt'保存到 options.filename 里。當(dāng)調(diào)用 parser.args() 后,options.filename 的值就為'foo.txt'。
你也可以指定 add_option() 方法中 type 參數(shù)為其它值,如 int 或者 float 等等:

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

默認(rèn)地,type 為'string'。也正如上面所示,長(zhǎng)參數(shù)名也是可選的。其實(shí),dest 參數(shù)也是可選的。如果沒(méi)有指定 dest 參數(shù),將用命令行的參數(shù)名來(lái)對(duì) options 對(duì)象的值進(jìn)行存取。
store 也有其它的兩種形式: store_true 和 store_false ,用于處理帶命令行參數(shù)后面不 帶值的情況。如 -v,-q 等命令行參數(shù):

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

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

默認(rèn)值

parse_args() 方法提供了一個(gè) default 參數(shù)用于設(shè)置默認(rèn)值。如:

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():

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

生成程序幫助

optparse 另一個(gè)方便的功能是自動(dòng)生成程序的幫助信息。你只需要為 add_option() 方法的 help 參數(shù)指定幫助信息文本:

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]") 

當(dāng) optparse 解析到 -h 或者 –help 命令行參數(shù)時(shí),會(huì)調(diào)用 parser.print_help() 打印程序的幫助信息:

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 將會(huì)退出,不再解析其它的命令行參數(shù)。
以上面的例子來(lái)一步步解釋如何生成幫助信息:

① 自定義的程序使用方法信息(usage message):
 
usage = "usage: %prog [options] arg1 arg2" 
這行信息會(huì)優(yōu)先打印在程序的選項(xiàng)信息前。當(dāng)中的 %prog,optparse 會(huì)以當(dāng)前程序名的字符串來(lái)替代:如 os.path.basename.(sys.argv[0])。
如果用戶(hù)沒(méi)有提供自定義的使用方法信息,optparse 會(huì)默認(rèn)使用: “usage: %prog [options]”。
② 用戶(hù)在定義命令行參數(shù)的幫助信息時(shí),不用擔(dān)心換行帶來(lái)的問(wèn)題,optparse 會(huì)處理好這一切。
③ 設(shè)置 add_option 方法中的 metavar 參數(shù),有助于提醒用戶(hù),該命令行參數(shù)所期待的參數(shù),如 metavar=“mode”:

-m MODE, --mode=MODE 

注意: metavar 參數(shù)中的字符串會(huì)自動(dòng)變?yōu)榇髮?xiě)。
④ 在 help 參數(shù)的幫助信息里使用 %default 可以插入該命令行參數(shù)的默認(rèn)值。

如果程序有很多的命令行參數(shù),你可能想為他們進(jìn)行分組,這時(shí)可以使用 OptonGroup:

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) 

下面是將會(huì)打印出來(lái)的幫助信息:

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 一樣,你可以在創(chuàng)建 OptionParser 對(duì)象時(shí),指定其 version 參數(shù),用于顯示當(dāng)前程序的版本信息:

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

 
這樣,optparse 就會(huì)自動(dòng)解釋 –version 命令行參數(shù):

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

處理異常

包括程序異常和用戶(hù)異常。這里主要討論的是用戶(hù)異常,是指因用戶(hù)輸入無(wú)效的、不完整的命令行參數(shù)而引發(fā)的異常。optparse 可以自動(dòng)探測(cè)并處理一些用戶(hù)異常:

$ /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 

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

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

上面的例子,當(dāng) -b 和 -b 命令行參數(shù)同時(shí)存在時(shí),會(huì)打印出“options -a and -b are mutually exclusive“,以警告用戶(hù)。
如果以上的異常處理方法還不能滿(mǎn)足要求,你可能需要繼承 OptionParser 類(lèi),并重載 exit() 和 erro() 方法。

完整的程序例子如下:

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() 

相信本文所述對(duì)大家的Python程序設(shè)計(jì)有一定的借鑒價(jià)值。

相關(guān)文章

  • Django自定義YamlField實(shí)現(xiàn)過(guò)程解析

    Django自定義YamlField實(shí)現(xiàn)過(guò)程解析

    這篇文章主要介紹了Django自定義YamlField實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11
  • python?manage.py?createsuperuser運(yùn)行錯(cuò)誤問(wèn)題解決

    python?manage.py?createsuperuser運(yùn)行錯(cuò)誤問(wèn)題解決

    這篇文章主要介紹了python?manage.py?createsuperuser運(yùn)行錯(cuò)誤,本文給大家分享錯(cuò)誤復(fù)現(xiàn)及解決方案,感興趣的朋友一起看看吧
    2023-10-10
  • Python內(nèi)置的HTTP協(xié)議服務(wù)器SimpleHTTPServer使用指南

    Python內(nèi)置的HTTP協(xié)議服務(wù)器SimpleHTTPServer使用指南

    這篇文章主要介紹了Python內(nèi)置的HTTP協(xié)議服務(wù)器SimpleHTTPServer使用指南,SimpleHTTPServer本身的功能十分簡(jiǎn)單,文中介紹了需要的朋友可以參考下
    2016-03-03
  • python使用tkinter實(shí)現(xiàn)簡(jiǎn)單計(jì)算器

    python使用tkinter實(shí)現(xiàn)簡(jiǎn)單計(jì)算器

    這篇文章主要為大家詳細(xì)介紹了python使用tkinter實(shí)現(xiàn)簡(jiǎn)單計(jì)算器,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • Python定時(shí)任務(wù)框架APScheduler安裝使用詳解

    Python定時(shí)任務(wù)框架APScheduler安裝使用詳解

    這篇文章主要介紹了Python定時(shí)任務(wù)框架APScheduler安裝使用詳解,重點(diǎn)介紹如何使用APscheduler實(shí)現(xiàn)python定時(shí)任務(wù),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)Python定時(shí)任務(wù)APScheduler相關(guān)知識(shí)感興趣的朋友一起看看吧
    2022-05-05
  • Python3 max()函數(shù)基礎(chǔ)用法

    Python3 max()函數(shù)基礎(chǔ)用法

    在本篇文章中我們給大家講述了關(guān)于Python3 max()函數(shù)的基本用法以及相關(guān)知識(shí)點(diǎn)內(nèi)容,需要的朋友們學(xué)習(xí)下。
    2019-02-02
  • Python中time庫(kù)的使用(日期時(shí)間)

    Python中time庫(kù)的使用(日期時(shí)間)

    time庫(kù)是python中處理時(shí)間的標(biāo)準(zhǔn)庫(kù),這篇文章主要介紹了Python中time庫(kù)的使用(日期時(shí)間),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-02-02
  • python中time、datetime模塊的使用

    python中time、datetime模塊的使用

    這篇文章主要介紹了python中time、datetime模塊的使用,幫助大家更好的利用python處理時(shí)間,感興趣的朋友可以了解下
    2020-12-12
  • python實(shí)現(xiàn)RGB與YCBCR顏色空間轉(zhuǎn)換

    python實(shí)現(xiàn)RGB與YCBCR顏色空間轉(zhuǎn)換

    這篇文章主要介紹了python實(shí)現(xiàn)RGB與YCBCR顏色空間轉(zhuǎn)換,RGB與YCbCr顏色空間概念的與變換關(guān)系,包括內(nèi)容灰度值和亮度的關(guān)系、RGB顏色空間與顏色控制、YCbCr顏色空間及與RGB的變換關(guān)系,需要的小伙伴可以參考一下
    2022-03-03
  • Python Counting Bloom Filter原理與實(shí)現(xiàn)詳細(xì)介紹

    Python Counting Bloom Filter原理與實(shí)現(xiàn)詳細(xì)介紹

    這篇文章主要介紹了Python Counting Bloom Filter原理與實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧
    2022-10-10

最新評(píng)論