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

  • 相关阅读:
    火狐flash插件
    centos 安装php ide (eclipse + php 插件)
    编译器的工作过程
    php中调用mysql的存储过程和存储函数
    mysql 高性能
    存储过程/游标/mysql 函数
    php 生成二维码
    frameset,frame应用,常用于后台
    html5 meta头部设置
    CAReplicatorLayer复制Layer和动画, 实现神奇的效果
  • 原文地址:https://www.cnblogs.com/zdwu/p/9182211.html
Copyright © 2011-2022 走看看