一 命令行參數:
(1)在python中:
*sys.argv:命令行參數的列表。
*len(sys.argv):命令行參數的個數(argc)。
*python中提供了三個模塊來輔助處理命令行參數:getopt,optparse和argparse。
(2)術語:
*argument:命令行上的字符串,在python中參數是sys.argv[1:],argv[0]是執行程序的名字。
*option:選項。
*option argument:選項的值,跟在選項後面。格式:-f foo/-ffoo,--file foo/--file=foo。
*position argument:位置參數,選項被處理後剩下的參數。
*required option。
二 getopt模塊:
(1)簡單用法:
*簡單的識別選項以及選項參數,位置參數以列表的形式返回。
三 optparse模塊(從2.7開始廢棄,建議使用argparse):
(1)簡單用法:
*識別選項以及選項參數,可指定複雜的操作,位置參數以列表的形式返回。如下:
from optparse import OptionParser
parser=OptionParser()
parser.add_option(“-f”, "--file", dest="filename", action="store" help="need a file name")。
(options,args)=parser.parse_args()
*使用時-f 選項值或--file選項值。
*action的值默認是“store”,把選項後面的賦給dest代表的值,即filename=選項值。
*optparse自動爲程序提供幫助信息,使用方式-h,--help。add_option函數中的help的值作爲查看程序幫助信息時可以看到。
*上例程序的幫助信息是:-l filename,--list=filename need a filename。注意filename就是dest的值,後面的信息就是help的值。
*parse_args():返回兩個值,options和args。options是一個字典,其值爲{"filename":選項值},可通過options.filename使用選項值;args是一個位置參數的列表,注意區分選項、選項參數以及位置參數。
(2)action的取值:
*store:默認。
*store_true
*store_false
*store_const:store a constant value.
*append:append this option's argument to a list.
*count:increment a counter by one.
*callback:call a specified function.
四 argparse模塊: