国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python中optionParser模塊的使用方法實例教程

2020-02-23 05:44:15
字體:
供稿:網(wǎng)友

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

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

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

另一個是 optparse,它功能強大,而且易于使用,可以方便地生成標準的、符合Unix/Posix 規(guī)范的命令行說明。

示例如下:

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()函數(shù)的解析,獲得選項,如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() 

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

<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 類,創(chuàng)建一個 OptionParser 對象:

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

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

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

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

parser.add_option("-f", "--file", ...)            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 武宣县| 天水市| 泸定县| 精河县| 祁连县| 靖安县| 海晏县| 诏安县| 常州市| 江北区| 云安县| 浦江县| 博罗县| 太保市| 赣州市| 福安市| 明水县| 庆安县| 景宁| 察雅县| 兴义市| 洪湖市| 云和县| 正镶白旗| 南投县| 仁寿县| 阿巴嘎旗| 丹阳市| 新安县| 大埔区| 鹰潭市| 崇仁县| 黄石市| 南华县| 庄河市| 张家口市| 临夏县| 德清县| 新津县| 磐石市| 大竹县|