python命令行选项和参数分割

python中使用getopt处理命令行参数,本文主要对getopt进行介绍。getopt的调用主要分三步:
1、导入sys和getopt模块;
2、分析命令行参数;
3、处理结果;

第一步很简单,只需要:

    import sys
    import getopt

第二步处理方法如下:

    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])
    except getopt.GetoptError:
        # print help information and exit:

1. 处理所使用的函数叫getopt() ,因为是直接使用import 导入的getopt 模块,所以要加上限定getopt 才可以。
2. 使用sys.argv[1:] 过滤掉第一个参数(它是执行脚本的名字,不应算作参数的一部分)。
3. 使用短格式分析串"ho:" 。当一个选项只是表示开关状态时,即后面不带附加参数时,在分析串中写入选项字符。当选项后面是带一个附加参数时,在分析串中写入选项字符同时后面加一个":" 号 。所以"ho:" 就表示"h" 是一个开关选项;"o:" 则表示后面应该带一个参数。
4. 使用长格式分析串列表:["help", "output="] 。长格式串也可以有开关状态,即后面不跟"=" 号。如果跟一个等号则表示后面还应有一个参数 。这个长格式表示"help" 是一个开关选项;"output=" 则表示后面应该带一个参数。
5. 调用getopt 函数。函数返回两个列表:opts 和args 。opts 为分析出的格式信息。args 为不属于格式信息的剩余的命令行参数。opts 是一个两元组的列表。每个元素为:( 选项串, 附加参数) 。如果没有附加参数则为空串'' 。
6. 整个过程使用异常来包含,这样当分析出错时,就可以打印出使用信息来通知用户如何使用这个程序。

如上面解释的一个命令行例子为:
'-h -o file --help --output=out file1 file2'

在分析完成后,opts 应该是:
[('-h', ''), ('-o', 'file'), ('--help', ''), ('--output', 'out')]

而args 则为:
['file1', 'file2']

第三步主要是对分析出的参数进行判断,并进行下一步的处理。主要处理模式如下:

    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        if o in ("-o", "--output"):
            output = a

使用一个循环,每次从opts 中取出一个两元组,赋给两个变量。o 保存选项参数,a 为附加参数。接着对取出的选项参数进行处理。

实践篇1:

    #!/usr/bin/env python

    import sys;
    import getopt;

    def usage():
        print("Usage:%s [-a|-o|-c] [--help|--output] args...." %Dsys.argv[0]);


    if "__main__" == __name__:
        #lsArgs = [""];
        
        try:
            opts,args = getopt.getopt(sys.argv[1:], "ao:c", ["help", "output="]);
        
            print("============ opts ==================");
            print(opts);
        
            print("============ args ==================");
            print(args);
            
            #check all param
            for opt,arg in opts:
                if opt in ("-h", "--help"):
                    usage();
                    sys.exit(1);
                elif opt in ("-t", "--test"):
                    print("for test option");
                else:
                    print("%s ==> %s" %(opt, arg));
            
        except getopt.GetoptError:
            print("getopt error!");
            usage();
            sys.exit(1);


运行结果:

$ ./test_getopt.py  -a -oaaa -caa --output=out file1 t file2 -d
============ opts ==================
[('-a', ''), ('-o', 'aaa'), ('-c', ''), ('-a', ''), ('-a', ''), ('--output', 'out')]
============ args ==================
['file1', 't', 'file2', '-d']
-a  ==>
-o  ==> aaa
-c  ==>
-a  ==>
-a  ==>
--output  ==> out


实践篇2:
    import sys, getopt

    def usage():
        print \
        '''
    Usage:convert.py [<-i input_file>
                      <-o output_file>
                      [-h or --help]
                      ]

    Options:
    -i: input_file
    -o: output_file
    -h or --help: help

    Example:convert.py -i test1 -o test2
    '''


    shortargs = 'hi:o:'
    longargs = 'help'
    opts, args = getopt.getopt(sys.argv[1:], shortargs,[longargs])
    print opts
    print args

    input_file = ''
    output_file = ''

    for op , value in opts:
        if op == '-i':
            input_file = value
        elif op == '-o':
            output_file = value
        elif op in ('-h','--help'):
            usage()
            sys.exit()

本实践中,定义shortargs时,有多个参数,假如后面没有longargs,“o”后面的":"必须带上,表示其为opts,而不是args;

原文地址:http://blog.chinaunix.net/uid-631981-id-3778547.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值