在Diveintopython的第十章,用到getopt模块中getopt函数,getopt模块用来处理命令行参数。看了码源的__doc__感觉不是很清楚,度娘了一下,原来__doc__中"""The return value consists of two elements: the first is a list of (option, value) pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of the first argument). """
它的意思是:在命令行输入: python test.py -i 127.0.0.1 -p 80 55 66
opts返回是个包含元祖的列表,每个元祖是分析出来的格式信息,比如 [('-i','127.0.0.1'),('-p','80')] ;
args 是个列表,包含那些没有‘-’或‘--’的参数,比如:['55','66']
总结测试:
测试结果:#!/usr/bin/env python import sys; import getopt; def usage(): print("Usage:%s [-h|-o|-t] [--help|--output] args...." %sys.argv[0]); if "__main__" == __name__: try: opts,args = getopt.getopt(sys.argv[1:], "ho:t", ["help", "output="]); print("============ opts =================="); print(opts); print("============ args =================="); print(args); #check all param for opt,arg in opts: if opt in ("-h", "--help"): usage(); sys.exit(1); elif opt in ("-t", "--test"): print("for test option"); else: print("%s ==> %s" %(opt, arg)); except getopt.GetoptError: print("getopt error!"); usage(); sys.exit(1);