zoukankan      html  css  js  c++  java
  • Python 处理脚本的命令行参数-getopt

    # -*- coding:utf-8 -*-
    import sys
    
    def test():
        """
        参数列表:sys.argv
        参数个数:len(sys.argv) 
        脚本名: sys.argv[0] 
        参数1:  sys.argv[1] 
        参数2:  sys.argv[2]
        """
        print "参数个数为:"+ str(len(sys.argv))
        print "参数列表为:"+ str(sys.argv)
        print "脚本名为:"+ sys.argv[0]
        for i in range(1, len(sys.argv)):
            print ""+str(i)+"个参数:"+sys.argv[i]
        
    test()

    Q: 如何识别到命令行选项(-u, -p)呢

    A: getopt模块,支持短选项模式(-)和长选项模式(-)

    1. getopt.getopt 方法:

    getopt.getopt 方法用于解析命令行参数列表,语法格式如下:

    getopt.getopt(args, options[, long_options])

    方法参数说明:

    • args: 要解析的命令行参数列表。

    • options: 以字符串的格式定义,options后的冒号(:)表示该选项必须有附加的参数,不带冒号表示该选项不附加参数。

    • long_options: 以列表的格式定义,long_options 后的等号(=)表示如果设置该选项,必须有附加的参数,否则就不附加参数。

    • 该方法返回值由两个元素组成: 第一个是 (option, value) 元组的列表。 第二个是参数列表,包含那些没有’-‘或’–’的参数

    2 Exception getopt.GetoptError

    在没有找到参数列表,或选项的需要的参数为空时会触发该异常。

    异常的参数是一个字符串,表示错误的原因。属性 msg 和 opt 为相关选项的错误信息。

    3. 例子:

    def getCmdPar(argv):
        """
            通过命令行得到脚本传递参数
        """
    
        plattype_cmd = ''
        version_cmd = ''
    
        try:
            """
                options, args = getopt.getopt(args, shortopts, longopts=[])
    
                参数args:一般是sys.argv[1:]。过滤掉sys.argv[0],它是执行脚本的名字,不算做命令行参数。
                参数shortopts:短格式分析串。例如:"ht:v:",h后面没有冒号,表示后面不带参数;t和v后面带有冒号,表示后面带参数。
                参数longopts:长格式分析串列表。例如:["help", "type=", "version="],help后面没有等号,表示后面不带参数;type和version后面带冒号,表示后面带参数。
    
                返回值options是以元组为元素的列表,每个元组的形式为:(选项串, 附加参数),如:('-i', '192.168.0.1')
                返回值args是个列表,其中的元素是那些不含'-'或'--'的参数。
            """
            opts, args = getopt.getopt(argv, "ht:v:", ["help", "type=", "version="])
        except getopt.GetoptError:
            print('Error: installTest.py -t <type> -v <version>')
            print('   or: installTest.py --type=<type> --version=<version>')
            sys.exit(2)
        
        # 处理 返回值options是以元组为元素的列表。    
        for opt, arg in opts:
            if opt in ("-h", "--help"):
                print(u'installTest.py -t <type> -p <version>')
                print(u'or: installTest.py --type=<type> --version=<version>')
                sys.exit()
            elif opt in ("-t", "--type"):
                plattype_cmd = arg
                #plattype.append(re.split('[,]', arg)) 
            elif opt in ("-v", "--version"):
                version_cmd = arg
                #version.append(re.split('[,]', arg)) 
        return plattype_cmd, version_cmd
  • 相关阅读:
    Visifire正式版(v1.1)发布
    [转]PSP机能强大!已能模拟运行WINDOWS系统?
    在Silverlight+WCF中应用以角色为基础的安全模式(一)基础篇之角色为基础的安全模式简介 Virus
    C#的加密解密算法,包括Silverlight的MD5算法 Virus
    MMORPG programming in Silverlight Tutorial (10)Implement the sprite’s 2D animation (Part IV)
    Game Script: Rescue Bill Gates
    MMORPG programming in Silverlight Tutorial (9)KeyFrame Animation
    MMORPG programming in Silverlight Tutorial (5)Implement the sprite’s 2D animation (Part II)
    MMORPG programming in Silverlight Tutorial (7)Perfect animation
    MMORPG programming in Silverlight Tutorial (3)Animate the object (Part III)
  • 原文地址:https://www.cnblogs.com/xiyuan2016/p/10083483.html
Copyright © 2011-2022 走看看