本文研究的主要是Python命令行解析模塊的相關(guān)內(nèi)容,具體如下。
Python命令行常見的解析器有兩種,一是getopt模塊,二是argparse模塊。下面就解讀下這兩種解析器。
這個(gè)模塊可以幫助腳本解析命令行參數(shù),一般是sys.argv[1:]。它遵循著Unix的getopt()函數(shù)相同的約定(用-/--指定命令參數(shù))。這個(gè)模塊提供兩個(gè)函數(shù)(getopt.getopt()/getopt.gnu_getopt())和一個(gè)參數(shù)異常(getopt.GetoptError)。
這里重點(diǎn)介紹getopt.getopt()這個(gè)函數(shù)。
函數(shù)原型:getopt.getopt(args, options[, long_options])
這個(gè)函數(shù)有三個(gè)參數(shù):
當(dāng)給定的命令行參數(shù)解析不了的話,就會(huì)拋出GetoptError異常。
函數(shù)的返回值包含兩個(gè)元素:
下面看幾個(gè)Demo:
短選項(xiàng):
>>> importgetopt>>> args='-a -b -cfoo -d bar a1 a2'.split()>>> args['-a', '-b', '-cfoo', '-d', 'bar', 'a1','a2']>>> optlist, args= getopt.getopt(args,'abc:d:')>>> optlist[('-a', ''), ('-b', ''), ('-c', 'foo'),('-d', 'bar')]>>> args['a1', 'a2']長(zhǎng)選項(xiàng):
>>> s='--condition=foo --testing --output-file abc.def -x a1 a2'>>> args= s.split()>>> args['--condition=foo', '--testing','--output-file', 'abc.def', '-x', 'a1', 'a2']>>> optlist, args= getopt.getopt(args,'x', [...   'condition=','output-file=','testing'])>>> optlist[('--condition', 'foo'), ('--testing', ''),('--output-file', 'abc.def'), ('-x', '')]>>> args['a1', 'a2']在腳本當(dāng)中經(jīng)典的應(yīng)用實(shí)例:
importgetopt,sys defmain():  try:    opts, args = getopt.getopt(sys.argv[1:],"ho:v", ["help","output="])  except getopt.GetoptErroras err:    # print help information and exit:    printstr(err) # will print something like "option -a not recognized"    usage()    sys.exit(2)  output =None  verbose =False  for o, a in opts:    if o =="-v":      verbose =True    elif o in ("-h","--help"):      usage()      sys.exit()    elif o in ("-o","--output"):      output = a    else:      assertFalse,"unhandled option"  # ... if __name__ =="__main__":  main()argparse模塊使得編寫用戶友好的命令行接口非常容易。程序只需定義好它要求的參數(shù),然后argparse將負(fù)責(zé)如何從sys.argv中解析出這些參數(shù)。argparse模塊還會(huì)自動(dòng)生成幫助和使用信息并且當(dāng)用戶賦給程序非法的參數(shù)時(shí)產(chǎn)生錯(cuò)誤信息。
新聞熱點(diǎn)
疑難解答
圖片精選