1 # coding = utf-8 2 3 from optparse import OptionParser 4 from optparse import OptionGroup 5 6 usage = 'Usage: %prog [options] arg1 arg2 ...' 7 8 parser = OptionParser(usage,version='%prog 1.0') 9 #通過OptionParser類創建parser實例,初始參數usage中的%prog等同於os.path.basename(sys.argv[0]),即 10 #你當前所運行的腳本的名字,version參數用來顯示當前腳本的版本。 11 12 ''' 13 添加參數,-f、--file是長短options,有一即可。 14 15 action用來表示將option后面的值如何處理,比如: 16 XXX.py -f test.txt 17 經過parser.parse_args()處理后,則將test.txt這個值存儲進-f所代表的一個對象,即定義-f中的dest 18 即option.filename = 'test.txt' 19 action的常用選項還有store_true,store_false等,這兩個通常在布爾值的選項中使用。 20 21 metavar僅在顯示幫助中有用,如在顯示幫助時會有: 22 -f FILE, --filename=FILE write output to FILE 23 -m MODE, --mode=MODE interaction mode: novice, intermediate, or expert 24 [default: intermediate] 25 如果-f這一項沒有metavr參數,則在上面會顯示為-f FILENAME --filename=FILENAME,即會顯示dest的值 26 27 defalut是某一選項的默認值,當調用腳本時,參數沒有指定值時,即采用default的默認值。 28 ''' 29 30 parser.add_option('-f','--file', 31 action='store',dest='filename', 32 metavar='FILE',help='write output to FILE') 33 34 parser.add_option('-m','--mode', 35 default = 'intermediate', 36 help='interaction mode:novice,intermediate,or expert [default:%default]') 37 parser.add_option('-v','--verbose', 38 action='store_true',dest='verbose',default=True, 39 help='make lots of noise [default]') 40 41 parser.add_option('-q','--quiet', 42 action='store_false',dest='verbose', 43 help="be vewwy quiet (I'm hunting wabbits)") 44 45 group = OptionGroup(parser,'Dangerous Options', 46 'Caution: use these options at your own risk.' 47 'It is believed that some of them bite.') 48 #調用OptionGroup類,定制以組顯示的option 49 50 group.add_option('-g',action='store_true',help='Group option.') 51 #添加option 52 parser.add_option_group(group) 53 #將剛定制的groupoption加入parser中 54 55 group = OptionGroup(parser,'Debug Options') 56 group.add_option('-d','--debug',action='store_true', 57 help='Print debug information.') 58 group.add_option('-s','--sql',action='store_true', 59 help='Print all SQL statements executed') 60 group.add_option('-e',action='store_true',help='Print every action done') 61 parser.add_option_group(group) 62 63 (options,args) = parser.parse_args() 64 #解析腳本輸入的參數值,options是一個包含了option值的對象 65 #args是一個位置參數的列表
python.exe xxx.py --help顯示結果如下:
Usage: test_optparse.py [options] arg1 arg2 ...
Options:
--version show program's version number and exit
-h, --help show this help message and exit
-f FILE, --file=FILE write output to FILE
-m MODE, --mode=MODE interaction mode:novice,intermediate,or expert
[default:intermediate]
-v, --verbose make lots of noise [default]
-q, --quiet be vewwy quiet (I'm hunting wabbits)
Dangerous Options:
Caution: use these options at your own risk.It is believed that some
of them bite.
-g Group option.
Debug Options:
-d, --debug Print debug information.
-s, --sql Print all SQL statements executed
-e Print every action done