您好,登錄后才能下訂單哦!
本文實(shí)例講述了Python處理命令行參數(shù)模塊optpars用法。分享給大家供大家參考,具體如下:
optpars是python中用來處理命令行參數(shù)的模塊,可以自動(dòng)生成程序的幫助信息,功能強(qiáng)大,易于使用,可以方便的生成標(biāo)準(zhǔn)的,符合Unix/Posix 規(guī)范的命令行說明。
使用 add_option()
來加入選項(xiàng),使用 parse_args() 來解析命令行。
add_option()中參數(shù)
第一個(gè)參數(shù)表示option的縮寫,以單個(gè)中劃線引導(dǎo),例如-f、-d,只能用單個(gè)字母,可以使用大寫;
第二個(gè)參數(shù)表示option的全拼,以兩個(gè)中劃線引導(dǎo),例如--file、--Opencv_version;
第一第二個(gè)參數(shù)可以單獨(dú)使用,也可以同時(shí)使用,但必須保證有其中一個(gè);
從第三個(gè)參數(shù)開始是命名參數(shù),是可選參數(shù),常用的幾個(gè):
type=: 表示輸入命令行參數(shù)的值的類型,默認(rèn)為string,可以指定為string, int, choice, float,complex其中一種;
default=: 表示命令參數(shù)的默認(rèn)值;
metavar=: 顯示到幫助文檔中用來提示用戶輸入期望的命令參數(shù);
dest=:指定參數(shù)在options對(duì)象中成員的名稱,如果沒有指定dest參數(shù),將用命令行參數(shù)名來對(duì)options對(duì)象的值進(jìn)行存取。
help=: 顯示在幫助文檔中的信息;
解析命令行
(options, args) = parse.parse_args()
或在main(argv)
函數(shù)里:
(options, args) = parser.parse_args(argv)
options,是一個(gè)對(duì)象(optpars.Values),保存有命令行參數(shù)值。通過命令行參數(shù)名,如 file,訪問其對(duì)應(yīng)的值: options.file ;
args,是一個(gè)由 positional arguments 組成的列表;
optparse使用
import sys from optparse import OptionParser parser = OptionParser() parser.add_option('-f','--file',type=str,default='./image',help='file path of images',dest='file_path') parser.add_option('--weights','-w',type=str,default='./weights_saved',help="file location of the trained network weights") parser.add_option('--iterations','-i',type=int,default=10000,help='iteration time of CRNN Net') parser.add_option('--gpu','-g',type=int,default=0,help="gpu id") def main(argv): (options, args) = parser.parse_args() (options, args) = parser.parse_args(argv) # both OK print 'file path of images: ' + options.file_path print "file location of the trained network weights: " + options.weights print 'iteration time of CRNN Net: ' + str(options.iterations) print 'gpu id: ' + str(options.gpu) if __name__ == '__main__': main(sys.argv)
查看幫助文檔:
python test.py -h
顯示:
Usage: test.py [options]
Options:
-h, --help show this help message and exit
-f FILE_PATH, --file=FILE_PATH
file path of images
-w WEIGHTS, --weights=WEIGHTS
file location of the trained network weights
-i ITERATIONS, --iterations=ITERATIONS
iteration time of CRNN Net
-g GPU, --gpu=GPU gpu id
輸入命令行參數(shù):
python test.py -f ../tensorflow/train_image -w ../tensorflow/weights -i 5000 -g 2
輸出:
file path of images: ../tensorflow/train_image
file location of the trained network weights: ../tensorflow/weights
iteration time of CRNN Net: 5000
gpu id: 2
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)學(xué)運(yùn)算技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。