python模塊之--optparse

optparse是用來在命令行添加選項的模塊,簡單命令行參數可以使用sys.argv[n]來實現,對於複雜的命令行參數使用optparse模塊會更加方便

示例代碼:opt.py

  1. #!/usr/bin/env python 
  2. import optparse 
  3. usage = "%prog [-F <from_step>]" 
  4. parser = optparse.OptionParser(usage) 
  5.  
  6. parser.add_option("-F","--from",dest="from_step",default=1,type="int",help="the from step,default 1",metavar="FROM_STEP"
  7. (options,args) = parser.parse_args() 
  8. print "options:%s" % options 
  9. print "args:%s" % args 
  10. print "from_step:%s" % options.from_step 

運行python opt.py -F 2 bob, 輸出選項和參數的值 如下

  1. options:{'from_step': 2} 
  2. args:['bob'] 
  3. from_step:2 

運行python opt.py -h, 輸出幫助信息如下

  1. Usage: opt.py [-F <from_step>
  2.  
  3. Options: 
  4.   -h, --help            show this help message and exit 
  5.   -F FROM_STEP, --from=FROM_STEP 
  6.                         the from step,default 1 

步驟:

1、產生OptionParser的對象parser。並傳入usage信息生成幫助信息的Usage部分

  1. usage = "%prog [-F <from_step>]" 
  2. parser = optparse.OptionParser(usage) 

2、調用OptionParser.add_option函數,添加選項

  1. parser.add_option("-F","--from",dest="from_step"
  2.                   default=1,type="int",help="the from step, 
  3.                   default 1,metavar="FROM_STEP"

add_option()的參數說明

首先是長短選項 -F和--from

action:存儲方式,分爲三種store,store_false,store_true

 

詳細分析:

 1)action="store"默認值,將命令行選項後面的值(示例中-F 2)和dest的值(from_step)組成字典({'from_step':2})並賦值給options,所以options.from_step的值爲2

 2)action="store_true",options.from_step的值是Ture,不是2

3)action="store_false",options.from_step的值是False,不是2

type:參數類型

dest:存儲的變量,即生成字典的key

default:設置參數的默認值

help:幫助信息

metavar:幫助信息中用到

3、調用OptionParser的parse_args函數生成字典和列表

  1. (options,args) = parser.parse_args() 

options是一個字典(帶選項的參數組成),args是一個列表(不帶選項的參數組成)

 

此外:調用OptionParser的print_help()函數會輸出幫助信息

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章