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

📄 opts.py

📁 xen虚拟机源代码安装包
💻 PY
📖 第 1 页 / 共 2 页
字号:
            output += '\nOptions:\n\n'            output += '\n'.join([str(o) for o in options])            output += '\n'        return output    def val_usage(self):        optvals = [s for s in self.options if s.optkeys[0][0] != '-']        output = ''        if optvals:            output += '\nValues:\n\n'            output += '\n'.join([str(o) for o in optvals])            output += '\n'        return output        def opt(self, name, **args):        """Add an option.        name    option name        **args  keyword params for option constructor        """        x = Opt(self, name, **args)        self.options.append(x)        self.options_map[name] = x        return x    def default(self, name):        self.default_opt = name    def getdefault(self, val):        if self.default_opt is None:            return 0        opt = self.option(self.default_opt)        return opt.set(val)    def var(self, name, **args):        x = OptVar(self, name, **args)        self.options.append(x)        self.options_map[name] = x        return x         def setvar(self, var, val):        """Set a default script variable.        """        self.vars[var] = val    def getvar(self, var):        """Get a default script variable.        """        return self.vars.get(var)    def option(self, name):        """Get an option (object).        """        return self.options_map.get(name)    def setopt(self, name, val):        """Set an option value.        An option can also be set using 'opts.vals.name = val'.        """        setattr(self.vals, name, val)    def getopt(self, name):        """Get an option value.        An option value can also be got using 'opts.vals.name'.        """        return getattr(self.vals, name)    def specified(self, name):        """Test if an option has been specified.        """        opt = self.option(name)        return opt and opt.specified()    def err(self, msg):        """Print an error to stderr and exit.        """        print >>sys.stderr, "Error:", msg        sys.exit(1)    def info(self, msg):        """Print a message to stdout (unless quiet is set).        """        if self.vals.quiet: return        print msg    def warn(self, msg):        """Print a warning to stdout.        """        print >>sys.stderr, "Warning:", msg    def parse(self, argv):        """Parse arguments argv using the options.        return remaining arguments        """        self.argv = argv        # hack to work around lack of gnu getopts parsing in python 2.2        args = argv[1:]        xargs = []        while args:            # let getopt parse whatever it feels like -- if anything            try:                (xvals, args) = getopt.getopt(args[0:],                                              self.short_opts(),                                              self.long_opts())            except getopt.GetoptError, err:                raise OptionError(str(err), self.use)            #self.err(str(err))                            for (k, v) in xvals:                for opt in self.options:                    if opt.specify(k, v): break                else:                    raise OptionError('Unknown option: %s' % k, self.use)            if not args:                break                        # then process the 1st arg             (arg,args) = (args[0], args[1:])            isvar = 0            if '=' in arg:                (k, v) = arg.split('=', 1)                for opt in self.options:                    if opt.specify(k, v):                        isvar = 1                        break            elif self.getdefault(arg):                isvar = 1            if not isvar:                xargs.append(arg)        return xargs    def short_opts(self):        """Get short options specifier for getopt.        """        l = []        for x in self.options:            y = x.short_opt()            if not y: continue            l.append(y)        return ''.join(l)    def long_opts(self):        """Get long options specifier for getopt.        """        l = []        for x in self.options:            y = x.long_opt()            if not y: continue            l.append(y)        return l    def usage(self):        print 'Usage: ', self.argv[0], self.use or 'OPTIONS'        print        if self.options:            for opt in self.options:                opt.show()                print            print    def var_usage(self):        if self.vars:            print 'The config file defines the following variables:'            for var in self.vars:                var.show()                print            print    def config_usage(self):        if self.imports:            print 'The following are automically imported:'            for x in self.imports:                print '   ', x            print        self.var_usage()    def load_defconfig(self, help=0):        """Load a defconfig script. Assumes these options set:        'path'    search path        'defconfig' script name        """        for x in [ '' ] + self.vals.path.split(':'):            if x:                p = os.path.join(x, self.vals.defconfig)            else:                p = self.vals.defconfig            if not p.startswith('/'):                p = os.path.join(os.path.curdir, p)            if os.path.exists(p):                self.info('Using config file "%s".' % p)                f = open(p)                is_xml = (f.read(1) == '<')                f.close()                if is_xml:                    raise XMLFileError(p)                self.load(p, help)                break        else:            raise OptionError('Unable to open config file: %s' % \                              self.vals.defconfig,                              self.use)    def load(self, defconfig, help):        """Load a defconfig file. Local variables in the file        are used to set options with the same names.        Variables are not used to set options that are already specified.        """        # Create global and local dicts for the file.        # Initialize locals to the vars.        # Use exec to do the standard imports and        # define variables we are passing to the script.        globs = {}        locs = {}        locs.update(self.vars)        cmd = '\n'.join(self.imports +                         [ "from xen.xm.help import Vars",                          "xm_file = '%s'" % defconfig,                          "xm_help = %d" % help,                          "xm_vars = Vars(xm_file, xm_help, locals())"                          ])        exec cmd in globs, locs        try:            execfile(defconfig, globs, locs)        except SyntaxError,e:                raise SyntaxError, \                "Errors were found at line %d while processing %s:\n\t%s"\                %(e.lineno,defconfig,e.text)        except:            if not help: raise        if help:            self.config_usage()            return        # Extract the values set by the script and set the corresponding        # options, if not set on the command line.        vtypes = [ types.StringType,                   types.ListType,                   types.IntType,                   types.FloatType                   ]        for (k, v) in locs.items():            if self.specified(k): continue            if not(type(v) in vtypes): continue            self.setopt(k, v)def set_true(opt, k, v):    """Set an option true."""    opt.set(1)def set_false(opt, k, v):    """Set an option false."""    opt.set(0)def set_bool(opt, k, v):    """Set a boolean option.    """    if v in ('yes', 'y'):        opt.set(1)    elif v in ('no', 'n'):        opt.set(0)    else:        opt.opts.err('Invalid value:' +v)        def set_value(opt, k, v):    """Set an option to a value."""    opt.set(v)def set_int(opt, k, v):    """Set an option to an integer value."""    try:        v = int(v)    except:        opt.opts.err('Invalid value: ' + str(v))    opt.set(v)def set_long(opt, k, v):    """Set an option to a long integer value."""    try:        v = long(v)    except:        opt.opts.err('Invalid value: ' + str(v))    opt.set(v)def set_float(opt, k, v):    """Set an option to a float value."""    try:        v = float(v)    except:        opt.opts.err('Invalid value: ' + str(v))    opt.set(v)def append_value(opt, k, v):    """Append a value to a list option."""    opt.append(v)def set_var(opt, k, v):    """Set a default script variable.    """    (var, val) = v.strip().split('=', 1)    opt.opts.setvar(var.strip(), val.strip())

⌨️ 快捷键说明

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