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

📄 optionsclass.py

📁 用python实现的邮件过滤器
💻 PY
📖 第 1 页 / 共 3 页
字号:
"""OptionsClassClasses:    Option - Holds information about an option    OptionsClass - A collection of optionsAbstract:This module is used to manage "options" managed in user editable files.This is the implementation of the Options.options globally shared optionsobject for the SpamBayes project, but is also able to be used to manageother options required by each application.The Option class holds information about an option - the name of theoption, a nice name (to display), documentation, default value,possible values (a tuple or a regex pattern), whether multiple valuesare allowed, and whether the option should be reset when restoring todefaults (options like server names should *not* be).The OptionsClass class provides facility for a collection of Options.It is expected that manipulation of the options will be carried outvia an instance of this class.Experimental or deprecated options are prefixed with 'x-', borrowing thepractice from RFC-822 mail.  If the user sets an option like:    [Tokenizer]    x-transmogrify: Trueand an 'x-transmogrify' or 'transmogrify' option exists, it is set silentlyto the value given by the user.  If the user sets an option like:    [Tokenizer]    transmogrify: Trueand no 'transmogrify' option exists, but an 'x-transmogrify' option does,the latter is set to the value given by the users and a deprecation messageis printed to standard error.To Do: o Stop allowing invalid options in configuration files o Find a regex expert to come up with *good* patterns for domains,   email addresses, and so forth. o str(Option) should really call Option.unconvert since this is what   it does.  Try putting that in and running all the tests. o [See also the __issues__ string.] o Suggestions?"""# This module is part of the spambayes project, which is Copyright 2002-3# The Python Software Foundation and is covered by the Python Software# Foundation license.__credits__ = "All the Spambayes folk."# blame for the new format: Tony Meyer <ta-meyer@ihug.co.nz>__issues__ = """Things that should be considered further and byother people:We are very generous in checking validity when multiple values areallowed and the check is a regex (rather than a tuple).  Any sequencethat does not match the regex may be used to delimit the values.For example, if the regex was simply r"[\d]*" then these would allbe considered valid:"123a234" -> 123, 234"123abced234" -> 123, 234"123XST234xas" -> 123, 234"123 234" -> 123, 234"123~!@$%^&@234!" -> 123, 234If this is a problem, my recommendation would be to change themultiple_values_allowed attribute from a boolean to a regex/Nonei.e. if multiple is None, then only one value is allowed.  Otherwisemultiple is used in a re.split() to separate the input."""import sysimport osimport shutilfrom tempfile import TemporaryFiletry:    import cStringIO as StringIOexcept ImportError:    import StringIOimport reimport typesimport localetry:    True, False, boolexcept NameError:    # Maintain compatibility with Python 2.2    True, False = 1, 0    def bool(val):        return not not valtry:    import textwrapexcept ImportError:    # textwrap was added in 2.3    # We only use this for printing out errors and docstrings, so    # it doesn't need to be great (if you want it great, get a more    # recent Python!).  So we do it the dumb way; the textwrap code    # could be duplicated here if anyone cared.    def wrap(s):        length = 40        return [s[i:i+length].strip() for i in xrange(0, len(s), length)]else:    wrap = textwrap.wrap__all__ = ['OptionsClass',           'HEADER_NAME', 'HEADER_VALUE',           'INTEGER', 'REAL', 'BOOLEAN',           'SERVER', 'PORT', 'EMAIL_ADDRESS',           'PATH', 'VARIABLE_PATH', 'FILE', 'FILE_WITH_PATH',           'IMAP_FOLDER', 'IMAP_ASTRING',           'RESTORE', 'DO_NOT_RESTORE', 'IP_LIST',           'OCRAD_CHARSET',          ]MultiContainerTypes = (types.TupleType, types.ListType)class Option(object):    def __init__(self, name, nice_name="", default=None,                 help_text="", allowed=None, restore=True):        self.name = name        self.nice_name = nice_name        self.default_value = default        self.explanation_text = help_text        self.allowed_values = allowed        self.restore = restore        self.delimiter = None        # start with default value        self.set(default)    def display_name(self):        '''A name for the option suitable for display to a user.'''        return self.nice_name    def default(self):        '''The default value for the option.'''        return self.default_value    def doc(self):        '''Documentation for the option.'''        return self.explanation_text    def valid_input(self):        '''Valid values for the option.'''        return self.allowed_values    def no_restore(self):        '''Do not restore this option when restoring to defaults.'''        return not self.restore    def set(self, val):        '''Set option to value.'''        self.value = val    def get(self):        '''Get option value.'''        return self.value    def multiple_values_allowed(self):        '''Multiple values are allowed for this option.'''        return type(self.default_value) in MultiContainerTypes    def is_valid(self, value):        '''Check if this is a valid value for this option.'''        if self.allowed_values is None:            return False        if self.multiple_values_allowed():            return self.is_valid_multiple(value)        else:            return self.is_valid_single(value)    def is_valid_multiple(self, value):        '''Return True iff value is a valid value for this option.        Use if multiple values are allowed.'''        if type(value) in MultiContainerTypes:            for val in value:                if not self.is_valid_single(val):                    return False            return True        return self.is_valid_single(value)    def is_valid_single(self, value):        '''Return True iff value is a valid value for this option.        Use when multiple values are not allowed.'''        if type(self.allowed_values) == types.TupleType:            if value in self.allowed_values:                return True            else:                return False        else:            # special handling for booleans, thanks to Python 2.2            if self.is_boolean and (value == True or value == False):                return True            if type(value) != type(self.value) and \               type(self.value) not in MultiContainerTypes:                # This is very strict!  If the value is meant to be                # a real number and an integer is passed in, it will fail.                # (So pass 1. instead of 1, for example)                return False            if value == "":                # A blank string is always ok.                return True            avals = self._split_values(value)            # in this case, allowed_values must be a regex, and            # _split_values must match once and only once            if len(avals) == 1:                return True            else:                # either no match or too many matches                return False    def _split_values(self, value):        # do the regex mojo here        if not self.allowed_values:            return ('',)        try:            r = re.compile(self.allowed_values)        except:            print >> sys.stderr, self.allowed_values            raise        s = str(value)        i = 0        vals = []        while True:            m = r.search(s[i:])            if m is None:                break            vals.append(m.group())            delimiter = s[i:i + m.start()]            if self.delimiter is None and delimiter != "":                self.delimiter = delimiter            i += m.end()        return tuple(vals)    def as_nice_string(self, section=None):        '''Summarise the option in a user-readable format.'''        if section is None:            strval = ""        else:            strval = "[%s] " % (section)        strval += "%s - \"%s\"\nDefault: %s\nDo not restore: %s\n" \                 % (self.name, self.display_name(),                    str(self.default()), str(self.no_restore()))        strval += "Valid values: %s\nMultiple values allowed: %s\n" \                  % (str(self.valid_input()),                     str(self.multiple_values_allowed()))        strval += "\"%s\"\n\n" % (str(self.doc()))        return strval    def as_documentation_string(self, section=None):        '''Summarise the option in a format suitable for unmodified        insertion in HTML documentation.'''        strval = ["<tr>"]        if section is not None:            strval.append("\t<td>[%s]</td>" % (section,))        strval.append("\t<td>%s</td>" % (self.name,))        strval.append("\t<td>%s</td>" % \                      ", ".join([str(s) for s in self.valid_input()]))        default = self.default()        if isinstance(default, types.TupleType):            default = ", ".join([str(s) for s in default])        else:            default = str(default)        strval.append("\t<td>%s</td>" % (default,))        strval.append("\t<td><strong>%s</strong>: %s</td>" \                      % (self.display_name(), self.doc()))        strval.append("</tr>\n")        return "\n".join(strval)    def write_config(self, file):        '''Output value in configuration file format.'''        file.write(self.name)        file.write(': ')        file.write(self.unconvert())        file.write('\n')    def convert(self, value):        '''Convert value from a string to the appropriate type.'''        svt = type(self.value)        if svt == type(value):            # already the correct type            return value        if type(self.allowed_values) == types.TupleType and \           value in self.allowed_values:            # already correct type            return value        if self.is_boolean():            if str(value) == "True" or value == 1:                return True            elif str(value) == "False" or value == 0:

⌨️ 快捷键说明

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