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

📄 option_parser.py

📁 HP Deskjet D2368驱动,可以驱动任何HP 的打印机
💻 PY
📖 第 1 页 / 共 2 页
字号:
"""optik.option_parserProvides the OptionParser and Values classes.Cheetah modifications:  added "Cheetah.Utils.optik." prefix to  all intra-Optik imports."""__revision__ = "$Id: option_parser.py,v 1.1 2006/12/18 23:09:06 dwelch Exp $"# Copyright (c) 2001 Gregory P. Ward.  All rights reserved.# See the README.txt distributed with Optik for licensing terms.# created 2001/10/17, GPW (from optik.py)import sys, osimport typesfrom Cheetah.Utils.optik.option import Option, NO_DEFAULTfrom Cheetah.Utils.optik.errors import OptionConflictError, OptionValueError, BadOptionErrordef get_prog_name ():    return os.path.basename(sys.argv[0])SUPPRESS_HELP = "SUPPRESS"+"HELP"SUPPRESS_USAGE = "SUPPRESS"+"USAGE"STD_HELP_OPTION = Option("-h", "--help",                         action="help",                         help="show this help message and exit")STD_VERSION_OPTION = Option("--version",                            action="version",                            help="show program's version number and exit")class Values:    def __init__ (self, defaults=None):        if defaults:            for (attr, val) in defaults.items():                setattr(self, attr, val)    def _update_careful (self, dict):        """        Update the option values from an arbitrary dictionary, but only        use keys from dict that already have a corresponding attribute        in self.  Any keys in dict without a corresponding attribute        are silently ignored.        """        for attr in dir(self):            if dict.has_key(attr):                dval = dict[attr]                if dval is not None:                    setattr(self, attr, dval)    def _update_loose (self, dict):        """        Update the option values from an arbitrary dictionary,        using all keys from the dictionary regardless of whether        they have a corresponding attribute in self or not.        """        self.__dict__.update(dict)    def _update (self, dict, mode):        if mode == "careful":            self._update_careful(dict)        elif mode == "loose":            self._update_loose(dict)        else:            raise ValueError, "invalid update mode: %r" % mode    def read_module (self, modname, mode="careful"):        __import__(modname)        mod = sys.modules[modname]        self._update(vars(mod), mode)    def read_file (self, filename, mode="careful"):        vars = {}        execfile(filename, vars)        self._update(vars, mode)    def ensure_value (self, attr, value):        if not hasattr(self, attr) or getattr(self, attr) is None:            setattr(self, attr, value)        return getattr(self, attr)class OptionParser:    """    Class attributes:      standard_option_list : [Option]        list of standard options that will be accepted by all instances        of this parser class (intended to be overridden by subclasses).    Instance attributes:      usage : string        a usage string for your program.  Before it is displayed        to the user, "%prog" will be expanded to the name of        your program (os.path.basename(sys.argv[0])).      option_list : [Option]        the list of all options accepted on the command-line of        this program      _short_opt : { string : Option }        dictionary mapping short option strings, eg. "-f" or "-X",        to the Option instances that implement them.  If an Option        has multiple short option strings, it will appears in this        dictionary multiple times.      _long_opt : { string : Option }        dictionary mapping long option strings, eg. "--file" or        "--exclude", to the Option instances that implement them.        Again, a given Option can occur multiple times in this        dictionary.      _long_opts : [string]        list of long option strings recognized by this option        parser.  Should be equal to _long_opt.values().      defaults : { string : any }        dictionary mapping option destination names to default        values for each destination.      allow_interspersed_args : boolean = true        if true, positional arguments may be interspersed with options.        Assuming -a and -b each take a single argument, the command-line          -ablah foo bar -bboo baz        will be interpreted the same as          -ablah -bboo -- foo bar baz        If this flag were false, that command line would be interpreted as          -ablah -- foo bar -bboo baz        -- ie. we stop processing options as soon as we see the first        non-option argument.  (This is the tradition followed by        Python's getopt module, Perl's Getopt::Std, and other argument-        parsing libraries, but it is generally annoying to users.)      rargs : [string]        the argument list currently being parsed.  Only set when        parse_args() is active, and continually trimmed down as        we consume arguments.  Mainly there for the benefit of        callback options.      largs : [string]        the list of leftover arguments that we have skipped while        parsing options.  If allow_interspersed_args is false, this        list is always empty.      values : Values        the set of option values currently being accumulated.  Only        set when parse_args() is active.  Also mainly for callbacks.    Because of the 'rargs', 'largs', and 'values' attributes,    OptionParser is not thread-safe.  If, for some perverse reason, you    need to parse command-line arguments simultaneously in different    threads, use different OptionParser instances.        """     standard_option_list = [STD_HELP_OPTION]    def __init__ (self,                  usage=None,                  option_list=None,                  option_class=Option,                  version=None,                  conflict_handler="error"):        self.set_usage(usage)        self.option_class = option_class        self.version = version        self.set_conflict_handler(conflict_handler)        self.allow_interspersed_args = 1        # Create the various lists and dicts that constitute the        # "option list".  See class docstring for details about        # each attribute.        self._create_option_list()        # Populate the option list; initial sources are the        # standard_option_list class attribute, the 'option_list'        # argument, and the STD_VERSION_OPTION global (if 'version'        # supplied).        self._populate_option_list(option_list)        self._init_parsing_state()    # -- Private methods -----------------------------------------------    # (used by the constructor)    def _create_option_list (self):        self.option_list = []        self._short_opt = {}            # single letter -> Option instance        self._long_opt = {}             # long option -> Option instance        self._long_opts = []            # list of long options        self.defaults = {}              # maps option dest -> default value    def _populate_option_list (self, option_list):        if self.standard_option_list:            self.add_options(self.standard_option_list)        if self.version:            self.add_option(STD_VERSION_OPTION)        if option_list:            self.add_options(option_list)            def _init_parsing_state (self):        # These are set in parse_args() for the convenience of callbacks.        self.rargs = None        self.largs = None        self.values = None    # -- Simple modifier methods ---------------------------------------    def set_usage (self, usage):        if usage is None:            self.usage = "usage: %prog [options]"        elif usage is SUPPRESS_USAGE:            self.usage = None        else:            self.usage = usage    def enable_interspersed_args (self):        self.allow_interspersed_args = 1    def disable_interspersed_args (self):        self.allow_interspersed_args = 0    def set_conflict_handler (self, handler):        if handler not in ("ignore", "error", "resolve"):            raise ValueError, "invalid conflict_resolution value %r" % handler        self.conflict_handler = handler    def set_default (self, dest, value):        self.defaults[dest] = value    def set_defaults (self, **kwargs):        self.defaults.update(kwargs)    # -- Option-adding methods -----------------------------------------    def _check_conflict (self, option):        conflict_opts = []        for opt in option._short_opts:            if self._short_opt.has_key(opt):                conflict_opts.append((opt, self._short_opt[opt]))        for opt in option._long_opts:            if self._long_opt.has_key(opt):                conflict_opts.append((opt, self._long_opt[opt]))        if conflict_opts:            handler = self.conflict_handler            if handler == "ignore":     # behaviour for Optik 1.0, 1.1                pass            elif handler == "error":    # new in 1.2                raise OptionConflictError(                    "conflicting option string(s): %s"                    % ", ".join([co[0] for co in conflict_opts]),                    option)            elif handler == "resolve":  # new in 1.2                for (opt, c_option) in conflict_opts:                    if opt.startswith("--"):                        c_option._long_opts.remove(opt)                        del self._long_opt[opt]                    else:                        c_option._short_opts.remove(opt)                        del self._short_opt[opt]                    if not (c_option._short_opts or c_option._long_opts):                        self.option_list.remove(c_option)    def add_option (self, *args, **kwargs):        """add_option(Option)           add_option(opt_str, ..., kwarg=val, ...)        """        if type(args[0]) is types.StringType:            option = self.option_class(*args, **kwargs)        elif len(args) == 1 and not kwargs:            option = args[0]            if not isinstance(option, Option):                raise TypeError, "not an Option instance: %r" % option        else:            raise TypeError, "invalid arguments"        self._check_conflict(option)        self.option_list.append(option)        for opt in option._short_opts:            self._short_opt[opt] = option        for opt in option._long_opts:            self._long_opt[opt] = option            self._long_opts.append(opt)        if option.dest is not None:     # option has a dest, we need a default            if option.default is not NO_DEFAULT:                self.defaults[option.dest] = option.default            elif not self.defaults.has_key(option.dest):                self.defaults[option.dest] = None    def add_options (self, option_list):        for option in option_list:            self.add_option(option)    # -- Option query/removal methods ----------------------------------    def get_option (self, opt_str):        return (self._short_opt.get(opt_str) or                self._long_opt.get(opt_str))    def has_option (self, opt_str):        return (self._short_opt.has_key(opt_str) or                self._long_opt.has_key(opt_str))    def remove_option (self, opt_str):        option = self._short_opt.get(opt_str)        if option is None:            option = self._long_opt.get(opt_str)        if option is None:            raise ValueError("no such option %r" % opt_str)        for opt in option._short_opts:            del self._short_opt[opt]        for opt in option._long_opts:            del self._long_opt[opt]            self._long_opts.remove(opt)        self.option_list.remove(option)    # -- Option-parsing methods ----------------------------------------    def _get_args (self, args):        if args is None:            return sys.argv[1:]        else:            return args[:]              # don't modify caller's list    def parse_args (self, args=None, values=None):

⌨️ 快捷键说明

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