熱線電話:13121318867

登錄
首頁精彩閱讀Python處理命令行參數模塊optpars用法實例分析
Python處理命令行參數模塊optpars用法實例分析
2018-07-19
收藏

Python處理命令行參數模塊optpars用法實例分析

本文實例講述了Python處理命令行參數模塊optpars用法。分享給大家供大家參考,具體如下:
optpars是python中用來處理命令行參數的模塊,可以自動生成程序的幫助信息,功能強大,易于使用,可以方便的生成標準的,符合Unix/Posix 規范的命令行說明。
使用 add_option() 來加入選項,使用 parse_args() 來解析命令行。
add_option()中參數
第一個參數表示option的縮寫,以單個中劃線引導,例如-f、-d,只能用單個字母,可以使用大寫;
第二個參數表示option的全拼,以兩個中劃線引導,例如--file、--Opencv_version;
第一第二個參數可以單獨使用,也可以同時使用,但必須保證有其中一個;
從第三個參數開始是命名參數,是可選參數,常用的幾個:
type=: 表示輸入命令行參數的值的類型,默認為string,可以指定為string, int, choice, float,complex其中一種;
default=: 表示命令參數的默認值;
metavar=: 顯示到幫助文檔中用來提示用戶輸入期望的命令參數;
dest=:指定參數在options對象中成員的名稱,如果沒有指定dest參數,將用命令行參數名來對options對象的值進行存取。
help=:  顯示在幫助文檔中的信息;

解析命令行    
(options, args) = parse.parse_args()

或在main(argv)函數里:    
(options, args) = parser.parse_args(argv)

options,是一個對象(optpars.Values),保存有命令行參數值。通過命令行參數名,如 file,訪問其對應的值: options.file ;
args,是一個由 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

輸入命令行參數:    
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

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢