⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 opts.py

📁 xen虚拟机源代码安装包
💻 PY
📖 第 1 页 / 共 2 页
字号:
#============================================================================# This library is free software; you can redistribute it and/or# modify it under the terms of version 2.1 of the GNU Lesser General Public# License as published by the Free Software Foundation.## This library is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU# Lesser General Public License for more details.## You should have received a copy of the GNU Lesser General Public# License along with this library; if not, write to the Free Software# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA#============================================================================# Copyright (C) 2004, 2005 Mike Wray <mike.wray@hp.com># Copyright (C) 2005 XenSource Ltd.#============================================================================"""Object-oriented command-line option support."""import getoptimport osimport os.pathimport sysimport typesdef _line_wrap(text, width = 70):    lines = []    current_line = ''    words = text.strip().split()    while words:        word = words.pop(0)        if len(current_line) + len(word) + 1 < width:            current_line += word + ' '        else:            lines.append(current_line.strip())            current_line = word + ' '                if current_line:        lines.append(current_line.strip())    return linesdef wrap(text, width = 70):    """ Really basic textwrap. Useful because textwrap is not available    for Python 2.2, and textwrap.wrap ignores newlines in Python 2.3+.    """    if len(text) < width:        return [text]        lines = []    for line in text.split('\n'):        lines += _line_wrap(line, width)    return linesclass OptionError(Exception):    """Denotes an error in option parsing."""    def __init__(self, message, usage = ''):        self.message = message        self.usage = usage    def __str__(self):        return self.messageclass XMLFileError(Exception):    """Thrown is input is an XML File"""    def __init__(self, XMLFile):        self.XMLFile = XMLFile    def __str__(self):        return "XMLFileError: %s" % self.XMLFile    def getFile(self):        return self.XMLFileclass Opt:    """An individual option.    """    def __init__(self, opts, name, short=None, long=None,                 val=None, fn=None, use=None, default=None):        """Create an option.        opts    parent options object        name    name of the field it controls        short   short (1-char) command line switch (optional)        long    long command-line switch. Defaults to option name.        val     string used to print option args in help.                If val is not specified the option has no arg.        fn      function to call when the option is specified.        use     usage (help) string        default default value if not specified on command-line        """        self.opts = opts        self.name = name        self.short = short        if long is None:            long = name        self.long = long        self.val = val        self.use = use        self.default = default        self.optkeys = []        if self.short:            self.optkeys.append('-' + self.short)        if self.long:            self.optkeys.append('--' + self.long)        self.fn = fn        self.specified_opt = None        self.specified_val = None        self.value = None        self.set(default)    def reset(self):        self.specified_opt = None        self.specified_val = None        self.value = None        self.set(self.default)    def __repr__(self):        return self.name + '=' + str(self.specified_val)    def __str__(self):        """ Formats the option into:        '-k, --key     description'        """        PARAM_WIDTH = 20        if self.val:            keys = ', '.join(['%s=%s' % (k, self.val) for k in self.optkeys])        else:            keys = ', '.join(self.optkeys)        desc = wrap(self.use, 55)        if len(keys) > PARAM_WIDTH:            desc = [''] + desc                    wrapped = ('\n' + ' ' * (PARAM_WIDTH + 1)).join(desc)        return keys.ljust(PARAM_WIDTH + 1) + wrapped    def set(self, value):        """Set the option value.        """        self.opts.setopt(self.name, value)    def get(self):        """Get the option value.        """        return self.opts.getopt(self.name)    def append(self, value):        """Append a value to the option value.        """        v = self.get() or []        v.append(value)        self.set(v)    def short_opt(self):        """Short option spec.        """        if self.short:            if self.val:                return self.short + ':'            else:                return self.short        else:            return None    def long_opt(self):        """Long option spec.        """        if self.long:            if self.val:                return self.long + '='            else:                return self.long        else:            return None    def format(self, str, start='    ', out=sys.stdout):        """Print a string, with consistent indentation at the start of lines.        """        lines = str.split('\n')        for l in lines:            l = l.strip()            if start:                out.write(start)            out.write(l)            out.write('\n')    def show(self, out=sys.stdout):        sep = ' '        for x in self.optkeys:            out.write(sep)            out.write(x)            sep = ', '        if self.val:            out.write(' ')            out.write(self.val)        out.write('\n')        if self.use:            self.format(self.use, out=out);        if self.val:            self.format('Default ' + str(self.default or 'None'), out=out)    def specify(self, k, v):        """Specify the option. Called when the option is set        from the command line.        k  option switch used        v  optional value given (if any)        """        if k in self.optkeys:            if self.val is None and v:                self.opts.err("Option '%s' does not take a value" % k)            self.specified_opt = k            self.specified_val = v            if self.fn:                self.fn(self, k, v)            return 1        else:            return 0    def specified(self):        """Test whether the option has been specified: set        from the command line.        """        return self.specified_optclass OptVar(Opt):    """An individual option variable.    """    def __init__(self, opts, name,                 val=None, fn=None, use=None, default=None):        """Create an option.        opts    parent options object        name    name of the field it controls        val     string used to print option args in help.                If val is not specified the option has no arg.        fn      function to call when the option is specified.        use     usage (help) string        default default value if not specified on command-line        """        if val is None:            val = name.upper()        Opt.__init__(self, opts, name, val=val, fn=fn, use=use, default=default)        self.optkeys = []        self.optkeys.append(self.long)    def short_opt(self):        return None    def long_opt(self):        return None    def show(self, out=sys.stdout):        print >>out, ' %s=%s' % (self.optkeys[0], self.val)         if self.use:            self.format(self.use, out=out);        if self.val:            self.format('Default ' + str(self.default or 'None'), out=out)class OptVals:    """Class to hold option values.    """    def __init__(self):        self.quiet = Falseclass Opts:    """Container for options.    """    imports = ["import sys",               "import os",               "import os.path",               "from xen.util.ip import *",               ]    def __init__(self, use=None):        """Options constructor.        use  usage string        """        self.use = use        # List of options.        self.options = []        # Options indexed by name.        self.options_map = {}        # Command-line arguments.        self.argv = []        # Option values.        self.vals = OptVals()        # Variables for default scripts.        self.vars = {}        # Option to use for bare words.        self.default_opt = None    def reset(self):        self.vals = OptVals()        self.vars = {}        for opt in self.options:            opt.reset()    def __repr__(self):        return '\n'.join(map(str, self.options))    def __str__(self):        options = [s for s in self.options if s.optkeys[0][0] == '-']        output = ''        if options:

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -