python作為我們幹營運的重要的語言,肯定我們大家都寫了不少,我們寫東西不是為了給我們自己用,而是我們團隊或者更多人用。
那麼就不得不說下python下擷取參數的方法啦。python內建的模組optparse就是我們一直喜歡和常用的啦(當然也有getopt,但是沒這個好用)。廢話不說了,下面說說怎麼用吧!!
首先貼一下官方文檔地址:http://docs.python.org/2/library/optparse.html
講之前先引用下預設字型內建的例子:
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
(options, args) = parser.parse_args()
這裡引入了兩個參數,分別是: -f 和 -q 。 可以看到通過add_option函數添加選項。-f參數中,add_option函數參數上面依次是短選項,長選項,描述資訊,協助資訊,預設變數名。
下面的-q參數,是用來表示後面不需要跟參數的情況。add_option函數參數上面依次是短選項,長選項,儲存動作(預設是store、還有store_false和store_true),,預設值,協助資訊。
在action中:store_ture/store_false儲存相應的布爾值。這兩個動作被用於實現布爾開關。
除了上面出現的參數,還有type(表示參數的資料類型:有string,int等)。
我們還可以把參數進行分組,使用方法optparse.OptionGroup。
group = OptionGroup(parser, "title", "description")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)
然後還有version,usage, description的用法,完整的見下面截圖:
好了,貼一下運行結果:
root@AN-BT5:/apps/python# python test.py -h
Usage: test.py [options] arg1 arg2
this is a test script!!!
Options:
--version show program's version number and exit
-h, --help show this help message and exit
-f FILE, --file=FILE write report to FILE
-n NUMBER, --num=NUMBER
define number
-q, --quiet don't print status messages to stdout
title:
description
-g Group option.
root@AN-BT5:/apps/python# python test.py -n 1
{'number': 1, 'verbose': True, 'g': None, 'filename': None}
[]
root@AN-BT5:/apps/python# python test.py -n 1 -f test.txt
{'number': 1, 'verbose': True, 'g': None, 'filename': 'test.txt'}
[]
root@AN-BT5:/apps/python# python test.py -n 1 -f test.txt -g
{'number': 1, 'verbose': True, 'g': True, 'filename': 'test.txt'}
[]
root@AN-BT5:/apps/python# python test.py -n 1 -f test.txt -g 1
{'number': 1, 'verbose': True, 'g': True, 'filename': 'test.txt'}
['1']
root@AN-BT5:/apps/python# python test.py -n 1 -f test.txt -g
{'number': 1, 'verbose': True, 'g': True, 'filename': 'test.txt'}
[]
root@AN-BT5:/apps/python#
還有個函數print_help我們也經常用到,在校正的時候輸出help資訊。好了,最後在你指令碼裡面試試吧