python之optparse
Python有兩個內(nèi)建的模塊用來處理命令行參數(shù)
一個是getopt只能簡單處理命令行參數(shù)
一個是optparse,功能更強大,而且易于使用,可以方便地生成標(biāo)準(zhǔn)的,符合Unix/Posix規(guī)范的命令行說明,會自動負責(zé)-h幫助選項
#!/usr/bin/env python2.6
# coding: utf-8 import optparse # 一個幫助文檔解析字符串
hstr = '%prog custom help string'
parser = optparse.OptionParser(hstr, description='custom description', version='%prog 1.0')
parser.add_option('-i', '--input', action='store', dest='input', help='read input data from input file')
parser.add_option('-o', '--output', action='store', dest='output', help='write data to output file')
parser.add_option('-q', '--quite', action='store_false', dest='version', help='dont\'t print the version')
# parser.add_option('-v', '--version', action='store_true', dest='input', default=False, help='print the version'')
# parser.add_option('-v', '--input', action='store', dest='input', help='print the version') # parser.add_option('-v', '--input', action='store', dest='input', help='print the version') parser.add_option('-f', '--file', action='store', dest='file', help='file to hand')
parser.add_option('-a', '--add', action='append', dest='add', help='add to hand')
parser.add_option('-c', '--count', action='count', dest='count', help='count to hand')
parser.add_option('-d', '--count1', action='count', dest='count', help='count1 to hand') # parser.add_option('-v', '--version', dest='version') if parser.has_option('-f'):
print ('content -f')
parser.set_default('-f', 'myFile')
parser.remove_option('-f') if not parser.has_option('-f'):
print ('do not content -f') # 用一個數(shù)組模擬命令參數(shù)
testArgs = ['-i', 'someForInput', 'someForFile', 'someForFile1', '-q', '-a', 'test1 test2 test3', '-c', '-d', '-h']
options, args = parser.parser_args(testArgs) print 'option: %s' % options
print 'args: %s' % args if options.input:
print 'input in args: %s' % options.input if options.version:
print 'version 1.0.0' if options.add:
print 'add in args: %s' $ options.add print 'version in args', options.version
Optparse支持一般性GUN的選項方法,包括
無參選項:-v
有參選項:-p value , -para=value
參值一體:-pvalue(不支持長參數(shù))
合并選項:-abc,-abcp value(最后一個可以是有參的,其余均無參)
解析時,- 和 -- 的區(qū)別
- 就看后面的值,要是無參的,那就繼續(xù)讀下一個;要是有參,就把參數(shù)讀進來(分隔或一體)
-- 直接讀后面的值
optparse現(xiàn)在不更新了,更新版本叫argparse
optparse module
基本用法:
1 載入OptionParse類,新建對象:OptionParser()
2 添加選項:add_option(...)
3 參數(shù)解析:parse_args()
新建對象
parser = optparse.OptionParser()
形參包括:
def __init__(self,
usage=None,
option_list=None,
option_class=Option,
version=None,
conflict_handler="error",
description=None,
formatter=None,
add_help_option=True,
prog=None,
epilog=None):
新建選項:
可以使用:add_options,add_option_group,add_option
add_option: 方法在前面的參數(shù)為命令的選項,可以為等價的短名或長名,一般是前面為短名,后面為長名
可配置的參數(shù):
dest:可以決定解析后,取值時的屬性名,尤其適于有多個等價參數(shù),不指定時就是選項不加-的字符串
type:選項的值類型,值的默認類型為字符串,這里將值指定為其他類型
default:缺省值,沒有設(shè)置缺省值的為None
help:選項中有-h時打印help信息
metavar:表示顯示到help中選項的默認值
choices:當(dāng)type設(shè)置為choices時,需要設(shè)置此值
const:指定一個常量給選項,該常量值將用于后面store_const和append_const,一起合用
action:用于控制對選項和參數(shù)的處理,像無參數(shù)選項處理,可以設(shè)置為以下幾種字符串:
store:儲存值到dest指定的屬性,強制要求后面提供參數(shù)
store_true:當(dāng)使用該選項時,后面的dest設(shè)置為true,不跟參數(shù)
store_false:當(dāng)使用該選項時,后面的dest設(shè)置為false,常用于dest為同名2個以上選項時的處理, 不跟參數(shù)
append:儲存值到dest指定的屬性中,并且以數(shù)組形式,必須跟參數(shù)
store_const:用來存儲參數(shù)為const設(shè)置的值到dest指定的屬性當(dāng)中,常用于dest為同名2個以上選項時的處理,不跟參數(shù)
append_const:用來存儲參數(shù)為const設(shè)置的數(shù)組到dest指定的屬性,不跟參數(shù)
count:使用后將給存儲值到dest指定的屬性加1,可以統(tǒng)計參數(shù)中出現(xiàn)的次數(shù),用途不大,不跟參數(shù)
callback:后面指定回調(diào)函數(shù)名(不加括號),會將相應(yīng)的opt和args傳給回調(diào)函數(shù)
help,version:對應(yīng)幫助和版本,要另外自己設(shè)計時使用
當(dāng)action設(shè)置為store_true/store_false時,解析參數(shù)時,如果有值時為true/false,沒有值時為None
當(dāng)dest相同時,一個action設(shè)置為store_false,另一個action設(shè)置為store_true時,解析參數(shù)時,以后面出現(xiàn)的為準(zhǔn)
參數(shù)詳情
選項相關(guān)參數(shù)
可以用來同時設(shè)置多個選項的默認參數(shù)
def set_default(self, opt, value): def set_defaults(self, **kwargs):
檢查是否有相應(yīng)選項
def has_option(self, opt_str):
刪除選項
def remove_option(self, opt_str):
eg:
parser = OptionParser()
parser.add_option('-f', '--file', action='store', dest='file', help='file to handle')
if parser.has_option('-f'):
print('content -f')
parser.set_default('-f', 'myFile')
parser.remove_option('-f') if not parser.has_option('-f'):
print('do not content -f')
輸出
content -f
do not content -f
添加選項組add_option_group()
如果options很多的時候,可以進行分組,然后進行添加,分組的好處是,對一系列程序參數(shù)可以分一個組,如果有獨立的description,可以另外處理,使用如下:
group = OptionGroup(parser) #創(chuàng)建分組
group.add_option() #添加選項
parser.add_option_group(group) #將分組加入到解釋器
添加選項數(shù)組add_options([option1,...])
將各個Option對象放在一個列表里再一起添加
參數(shù)解析 parse_args()
使用parse_args()對參數(shù)進行解析,默認是使用sys.argv[1:]作為參數(shù),也可以傳遞一個命令行參數(shù)列表:parse_args(list)
parse_args有兩個值:
options:它是一個對象,保存有命令行參數(shù)值,只要知道命令行參數(shù)名,如input,就可以訪問其對應(yīng)的值:option.input
args:它是沒被解析的命令行參數(shù)列表
幫助文檔
默認自動帶有-h和--help來輸出幫助文檔,輸出后程序終止
幫助文檔由三部分組成:
usage幫助部分:usage幫助部分一般是在OptionParser初始化時輸入,為第一個參數(shù),也可以使用具體形參名指定,可以使用%prog來表示當(dāng)前的程序名
description描述部分:在初始化OptionParser時,description形參指定的內(nèi)容
選項以及選項說明部分:選項加入時定義的說明文字
OptionParser的形參version可以指定--version輸出的字符串,同樣支持%prog,如version="%prog 1.0"
# 一個幫助文檔解釋字符串
hstr = '%prog custom help string'
parser = OptionParser(hstr, description='custom description')
get_usage(),get_description(),get_version() 獲取對應(yīng)的字符串
print_help(),print_usage(),print_description(),print_version() 輸出相應(yīng)的內(nèi)容
error(str):出錯并輸出str
轉(zhuǎn)載
總結(jié)
以上是生活随笔為你收集整理的python之optparse的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PCIe事务层の详解(一)
- 下一篇: Golang中的OO(面向对象)