zoukankan      html  css  js  c++  java
  • 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解决。

  • 相关阅读:
    up6-chrome 45+安装教程
    HttpUploader7-授权码配置
    jsp-MySQL连接池
    WordPaster2-正式包布署说明
    HTTP文件上传插件开发文档-ASP
    HTTP文件上传插件开发文档-JSP
    eWebEditor9.x整合教程-Xproer.WordPaster
    42. Trapping Rain Water
    41. First Missing Positive
    40. Combination Sum II
  • 原文地址:https://www.cnblogs.com/zdwu/p/9182211.html
Copyright © 2011-2022 走看看