歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python getopt模塊處理命令行選項實例教程

Python getopt模塊處理命令行選項實例教程

日期:2017/3/1 9:35:44   编辑:Linux編程

分享下Python getopt模塊處理命令行選項的一些例子。在python編程中,getopt模塊與shell中的getopt參數模塊一樣靈活而實用。

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 的例子
# www.linuxidc.com
>>> 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']

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved