欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python getopt模塊處理命令行選項(xiàng)實(shí)例

 更新時(shí)間:2014年05月13日 10:55:05   作者:  
這篇文章主要介紹了Python getopt模塊處理命令行選項(xiàng)實(shí)例,本文講解相對(duì)簡(jiǎn)單,需要的朋友可以參考下

getopt模塊用于抽出命令行選項(xiàng)和參數(shù),也就是sys.argv
命令行選項(xiàng)使得程序的參數(shù)更加靈活。支持短選項(xiàng)模式和長(zhǎng)選項(xiàng)模式
例如  python scriptname.py -f 'hello' --directory-prefix=/home -t --format 'a' 'b'

復(fù)制代碼 代碼如下:

import getopt, sys
shortargs = 'f:t'
longargs = ['directory-prefix=', 'format']
opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )

getopt.getopt ( [命令行參數(shù)列表], '短選項(xiàng)', [長(zhǎng)選項(xiàng)列表] )

短選項(xiàng)名后的冒號(hào) : 表示該選項(xiàng)必須有附加的參數(shù)
長(zhǎng)選項(xiàng)名后的等號(hào) = 表示該選項(xiàng)必須有附加的參數(shù)

返回 opts 和 args
opts 是一個(gè)參數(shù)選項(xiàng)及其value的元組 ( ( '-f', 'hello'), ( '-t', '' ), ( '--format', '' ), ( '--directory-prefix', '/home' ) )
args 是一個(gè)除去有用參數(shù)外其他的命令行輸入 ( 'a', 'b' )  

復(fù)制代碼 代碼如下:
# 然后遍歷 opts 便可以獲取所有的命令行選項(xiàng)及其對(duì)應(yīng)參數(shù)了
for opt, val in opts:
    if opt in ( '-f', '--format' ):
        pass
    if ....

使用字典接受命令行的輸入,然后再傳送字典,可以使得命令行參數(shù)的接口更加健壯

# 兩個(gè)來自 python2.5 Documentation 的例子

復(fù)制代碼 代碼如下:

>>> import getopt, sys
>>> arg = '-a -b -c foo -d bar a1 a2'
>>> optlist, args = getopt.getopt( sys.argv[1:], 'abc:d:' )
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']

>>> arg = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> optlist, args = getopt.getopt( sys.argv[1:], 'x', ['condition=', 'output-file=', 'testing'] )
>>> optlist
[ ('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x','') ]
>>> args
['a1', 'a2']

相關(guān)文章

最新評(píng)論