getopt模塊用于抽出命令行選項和參數,也就是sys.argv
命令行選項使得程序的參數更加靈活。支持短選項模式和長選項模式
例如 python scriptname.py -f 'hello' --directory-prefix=/home -t --format 'a' 'b'
短選項名后的冒號 : 表示該選項必須有附加的參數
長選項名后的等號 = 表示該選項必須有附加的參數
返回 opts 和 args
opts 是一個參數選項及其value的元組 ( ( '-f', 'hello'), ( '-t', '' ), ( '--format', '' ), ( '--directory-prefix', '/home' ) )
args 是一個除去有用參數外其他的命令行輸入 ( 'a', 'b' )
# 兩個來自 python2.5 Documentation 的例子
>>> 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']
新聞熱點
疑難解答
圖片精選