使用usage.Options检查命令行参数

时间:2016-02-16 12:33:53

标签: python parameters twisted

我正在使用usage.Options解析和检查命令行参数。

#!/usr/bin/python

from twisted.python import usage
import sys

class Options(usage.Options):
    """
       Defines the default input parameters
    """
    optParameters = [
            ["param", "p", 1, "Int Parameter", int],
        ]

if __name__ == "__main__":

    options = Options()
    try:
        options.parseOptions()
    except Exception, e:
        print '%s: %s' % (sys.argv[0], e)
        print '%s: Try --help for usage details.' % (sys.argv[0])
        sys.exit(1)
    else:
        if options['param'] < 0 or options['param'] > 10: 
            print "param out of the range [0,10]"
            sys.exit(1)

我不知道如何检查输入param的值是否为数字。如果用户不小心插入了一封信,他会得到这个:

  

参数类型强制失败:int()with base的文字无效   10:&#39; d&#39;

1 个答案:

答案 0 :(得分:1)

为什么不使用optparse?

function rgbFun(a){
    //Define object either way
    //rgb = {'red':0,'blue':0,'green':0}; 
    rgb = {};
    var r = a.substr(0,3),
        b = a.splitOnLast('-')[1], //will check the last splitted value of blue
        g = a.splitOnLast('|')[1]; //will check the last splitted value of green
    rgb.red = r;
    if(b){
        rgb.blue = b.substr(1,3);
    }else{
        rgb.blue = 0;
    }
    if(g){
        rgb.green = g.substr(1,3);
    }else{
        rgb.green = 0;
    }
    return rgb;
}
rgbFun(CaseA);
//Result - {red: "123", blue: "244", green: "155"}
rgbFun(CaseB);
//Result - {red: "123", blue: "244", green: "155"}
rgbFun(CaseC);
//Result - {red: "123", blue: 0, green: "155"}

更新

你可以拥有这样的东西。添加并替换您想要的所有内容:

from optparse import OptionParser
options, args = parser.parse_args()

def args():
    parser = OptionParser(usage='usage: %prog [options]', version='%prog 1.0.0')
    parser.add_option(.....)
    return parser