Python getopt模組處理命令列選項執行個體

來源:互聯網
上載者:User
getopt模組用於抽出命令列選項和參數,也就是sys.argv
命令列選項使得程式的參數更加靈活。支援短選項模式和長選項模式
例如 python scriptname.py -f 'hello' --directory-prefix=/home -t --format 'a' 'b'
複製代碼 代碼如下:


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


getopt.getopt ( [命令列參數列表], '短選項', [長選項列表] )

短選項名後的冒號 : 表示該選項必須有附加的參數
長選項名後的等號 = 表示該選項必須有附加的參數

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

複製代碼 代碼如下:

# 然後遍曆 opts 便可以擷取所有的命令列選項及其對應參數了
for opt, val in opts:
if opt in ( '-f', '--format' ):
pass
if ....


使用字典接受命令列的輸入,然後再傳送字典,可以使得命令列參數的介面更加健壯

# 兩個來自 python2.5 Documentation 的例子
複製代碼 代碼如下:


>>> 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']

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.