getopt類(lèi)似linux shell getopt儿礼,提供命令行參數(shù)解析能力悴品。
Basic Concept
short option:start with the single hyphen(-), ls -a. 只能一個(gè)字符,格式為: -a [value]
long option: starts with the double hyphen(-) ls —all. 一個(gè)字符以上限书,格式為 —all [value]
option value: option可以攜帶value。
getopt.getopt(args, options[, long_options])
getopt short option和long option使用兩個(gè)參數(shù)指定,需要攜帶value時(shí)蜂怎,short option在option后跟”:”, long option在option后跟”=”
注意事項(xiàng)
getopt的option必須在參數(shù)之前,第一個(gè)非option字符后的所有字符都認(rèn)為是參數(shù)置尔。 ls -a arg1 -x的寫(xiě)法杠步,-x不會(huì)被解析為option
常規(guī)用法示例
# 引用自官方文檔
import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError as err:
# print help information and exit:
print str(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:
assert False, "unhandled option"
# ...
if __name__ == "__main__":
main()