码迷,mamicode.com
首页 > 其他好文 > 详细

getopt两个模块getopt 和gun_getopt 的异同

时间:2018-06-14 14:42:45      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:inf   argv   print   IV   top   ==   导致   解析   结果   

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解决。

 

getopt两个模块getopt 和gun_getopt 的异同

标签:inf   argv   print   IV   top   ==   导致   解析   结果   

原文地址:https://www.cnblogs.com/zdwu/p/9182211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!