getopt类似linux shell getopt,提供命令行参数解析能力。
Basic Concept
short option:start with the single hyphen(-), ls -a. 只能一个字符,格式为: -a [value]
long option: starts with the double hyphen(-) ls —all. 一个字符以上,格式为 —all [value]
option value: option可以携带value。
getopt.getopt(args, options[, long_options])
getopt short option和long option使用两个参数指定,需要携带value时,short option在option后跟”:”, long option在option后跟”=”
注意事项
getopt的option必须在参数之前,第一个非option字符后的所有字符都认为是参数。 ls -a arg1 -x的写法,-x不会被解析为option
常规用法示例
# 引用自官方文档
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()