getopt两个模块getopt 和gun_getopt 的异同

getopt的两个模块getopt和gun_getopt都可以接收参数,但是又有不同;

先看 getopt.getopt这个模块:

import sys
import getopt
def main(param):
    opts, args = getopt.getopt(param,"hc:s:")
    print("opts",opts )
    print("args",args)
    for opt,arg in opts:
        if opt == "-h":
            print('help')
        elif opt == "-c":
            chip = arg
        elif opt == '-s':
            seq = arg
    print('chip',chip,'seq',seq)
if __name__=='__main__':
    main(sys.argv[1:])

在命令行运行并得到结果,从结果看到-c 和-s 都得到正确解析,如下图:

但是如果我们换一种输入参数,得到结果不能正确解析,如下图: 发现从5之后就没有解析,这些没有解析的参数放在args当中,导致seq 变量声明,最终报错。

而实际情况有这种需要,比如如下情况,可用getopt.gnu_getopt模块:

import sys
import getopt
def main(param):
    opts, args = getopt.gnu_getopt(param,"hc:s:")
    print(opts, args)
    if len(args)== 1:
        if args[0]=="Model1":
            for opt,arg in opts:
                if opt == "-h":
                    sys.exit(0)
                elif opt == "-c":
                    chip = arg
            print('Molde1','chip',chip)
        elif args[0]=="Model2":
            for opt,arg in opts:
                if opt == "-h":
                    sys.exit(0)
                elif opt == "-c":
                    chip = arg
                elif opt == "-s":
                    seq = arg
            print('Molde1','chip',chip,'seq',seq)
if __name__=='__main__':
    main(sys.argv[1:])

在命令行输入参数,所有参数得到正常解析。

 

总结:getopt.gnu_getopt有getopt.getopt的基本接受参数功能,但是对参数中有 [option] 选项的时候,需要用getopt.getopt解决。

 

posted @ 2018-06-14 11:24  吴增丁  阅读(524)  评论(0编辑  收藏  举报