热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

openstacknova基础知识介绍之cfg

纠结了两天,才把nova中的配置文件的管理和命令行的解析了解了一个大概,在nova中,很多地方都用到了cfg这个模块。现在的分析,只是还在表面上,没有深入到实质性的内容,而且,有很多不清楚的地方,这个不清楚的地方,主要是不知道它用来是做什么的,以及

纠结了两天,才把nova中的配置文件的管理和命令行的解析了解了一个大概,在nova中,很多地方都用到了cfg这个模块。

现在的分析,只是还在表面上,没有深入到实质性的内容,而且,有很多不清楚的地方,这个不清楚的地方,主要是不知道它用来是做什么的,以及怎么去用它。不过随着慢慢的深入,会越来越清楚的。

我觉得cfg模块的主要作用有两个:一个是对配置文件进行解析,一个是对命令行参数进行解析,但是我不清楚的是这个解析的命令行参数是怎么用的,在哪里用。

相应的,有两个较为核心的类:MultiConfigParser和OptionParser,前者是对配置文件进行解析的,这个类是nova自己写的,后者是对命令行进行解析的,用的是python库中的类。这两个类最终整合到ConfigOpts类中,然后又派生出了CommonConfigOpts类,就是通过这个类和外面进行交互的。

整理了一个类图,来看一下整体的结构:

类图只是把主要的类以及主要的方法和变量罗列出来,还有其它很多类这里就没有详细列举了,先举一个简单的例子,来看一下最核心的东西,其它的都是在围绕这个核心进行了加工处理,首先来看对命令行解析的这一个功能,核心的代码可举例如下:

from optparse import OptionParser
[...]
parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")
group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk.  "
                    "It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)
(options, args) = parser.parse_args()
OptionParser这个类,就是对一个命令的解析,包括这个命令的各个选项,这些选项如何处理。如果对这个地方不懂的,可以去python标准库中找optparse这个模块。

在cfg中,进行了如下封装:

1. 把选项(option)封装成了一个类Opt,并且对不同的选项类型分别派生出了StrOpt,BoolOpt等

2. 对OptionGroup进行了封装,即OptGroup,里面维护了一个OptionGroup对象和一个_opts字典(用来存放Opt对象)

3. ConfigOpts类封装了OptGroup和Opt类,以及一个OptionParser类,这样这三个主角就融合在一起了,并且提供了register_*()方法,供外部调用,来向OptionParser对象添加选项(option)或组(group)

至于对配置文件的解析,则主要是MultiConfigParser类和ConfigParser类,两者是聚合的关系,MultiConfigParser提供了read()和get()方法,前者是解析配置文件,后者是读取配置文件中的信息,最终也聚合在了ConfigOpts中。

主要就这些内容吧,来看一个简单的测试:

import sys
from nova.openstack.common import cfg
import unittest
global_opts = [
    cfg.StrOpt('aws_access_key_id',
               default='admin',
               help='AWS Access ID'),
    cfg.IntOpt('glance_port',
               default=9292,
               help='default glance port'),
    cfg.BoolOpt('api_rate_limit',
                default=True,
                help='whether to rate limit the api'),
    cfg.ListOpt('enabled_apis',
                default=['ec2', 'osapi_compute', 'osapi_volume', 'metadata'],
                help='a list of APIs to enable by default'),
    cfg.MultiStrOpt('osapi_compute_extension',
                    default=[
                      'nova.api.openstack.compute.contrib.standard_extensions'
                      ],
                    help='osapi compute extension to load'),
]
mycfg=cfg.CONF
class TestCfg(unittest.TestCase):
    def setup(self):
        pass
    def test_find_config_files(self):
        config_files=cfg.find_config_files('nova')
        self.assertEqual(config_files, ['/etc/nova/nova.conf'])
    def test_register_opts(self):
        mycfg.register_opts(global_opts)
        aws_access_key_id=mycfg.__getattr__('aws_access_key_id')
        self.assertEqual(aws_access_key_id, 'admin')
    def test_cparser(self):
        mycfg([''],project='nova')
        print mycfg._cparser.parsed
        rabbit_host=mycfg._cparser.get('DEFAULT',['--rabbit_host'])
        self.assertEqual(rabbit_host, ['10.10.10.2'])
suite = unittest.TestLoader().loadTestsFromTestCase(TestCfg)
unittest.TextTestRunner(verbosity=2).run(suite)
加注释的源码():
# -*- coding: cp936 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Red Hat, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
r"""
Configuration options which may be set on the command line or in config files.
The schema for each option is defined using the Opt sub-classes, e.g.:
::
    common_opts = [
        cfg.StrOpt('bind_host',
                   default='0.0.0.0',
                   help='IP address to listen on'),
        cfg.IntOpt('bind_port',
                   default=9292,
                   help='Port number to listen on')
    ]
Options can be strings, integers, floats, booleans, lists or 'multi strings'::
    enabled_apis_opt = cfg.ListOpt('enabled_apis',
                                   default=['ec2', 'osapi_compute'],
                                   help='List of APIs to enable by default')
    DEFAULT_EXTENSIONS = [
        'nova.api.openstack.compute.contrib.standard_extensions'
    ]
    osapi_compute_extension_opt = cfg.MultiStrOpt('osapi_compute_extension',
                                                  default=DEFAULT_EXTENSIONS)
Option schemas are registered with the config manager at runtime, but before
the option is referenced::
    class ExtensionManager(object):
        enabled_apis_opt = cfg.ListOpt(...)
        def __init__(self, conf):
            self.conf = conf
            self.conf.register_opt(enabled_apis_opt)
            ...
        def _load_extensions(self):
            for ext_factory in self.conf.osapi_compute_extension:
                ....
A common usage pattern is for each option schema to be defined in the module or
class which uses the option::
    opts = ...
    def add_common_opts(conf):
        conf.register_opts(opts)
    def get_bind_host(conf):
        return conf.bind_host
    def get_bind_port(conf):
        return conf.bind_port
An option may optionally be made available via the command line. Such options
must registered with the config manager before the command line is parsed (for
the purposes of --help and CLI arg validation)::
    cli_opts = [
        cfg.BoolOpt('verbose',
                    short='v',
                    default=False,
                    help='Print more verbose output'),
        cfg.BoolOpt('debug',
                    short='d',
                    default=False,
                    help='Print debugging output'),
    ]
    def add_common_opts(conf):
        conf.register_cli_opts(cli_opts)
The config manager has two CLI options defined by default, --config-file
and --config-dir::
    class ConfigOpts(object):
        def __call__(self, ...):
            opts = [
                MultiStrOpt('config-file',
                        ...),
                StrOpt('config-dir',
                       ...),
            ]
            self.register_cli_opts(opts)
Option values are parsed from any supplied config files using
openstack.common.iniparser. If none are specified, a default set is used
e.g. glance-api.conf and glance-common.conf::
    glance-api.conf:
      [DEFAULT]
      bind_port = 9292
    glance-common.conf:
      [DEFAULT]
      bind_host = 0.0.0.0
Option values in config files override those on the command line. Config files
are parsed in order, with values in later files overriding those in earlier
files.
The parsing of CLI args and config files is initiated by invoking the config
manager e.g.::
    conf = ConfigOpts()
    conf.register_opt(BoolOpt('verbose', ...))
    conf(sys.argv[1:])
    if conf.verbose:
        ...
Options can be registered as belonging to a group::
    rabbit_group = cfg.OptGroup(name='rabbit',
                                title='RabbitMQ options')
    rabbit_host_opt = cfg.StrOpt('host',
                                 default='localhost',
                                 help='IP/hostname to listen on'),
    rabbit_port_opt = cfg.IntOpt('port',
                                 default=5672,
                                 help='Port number to listen on')
    def register_rabbit_opts(conf):
        conf.register_group(rabbit_group)
        # options can be registered under a group in either of these ways:
        conf.register_opt(rabbit_host_opt, group=rabbit_group)
        conf.register_opt(rabbit_port_opt, group='rabbit')
If it no group attributes are required other than the group name, the group
need not be explicitly registered e.g.
    def register_rabbit_opts(conf):
        # The group will automatically be created, equivalent calling::
        #   conf.register_group(OptGroup(name='rabbit'))
        conf.register_opt(rabbit_port_opt, group='rabbit')
If no group is specified, options belong to the 'DEFAULT' section of config
files::
    glance-api.conf:
      [DEFAULT]
      bind_port = 9292
      ...
      [rabbit]
      host = localhost
      port = 5672
      use_ssl = False
      userid = guest
      password = guest
      virtual_host = /
Command-line options in a group are automatically prefixed with the
group name::
    --rabbit-host localhost --rabbit-port 9999
Option values in the default group are referenced as attributes/properties on
the config manager; groups are also attributes on the config manager, with
attributes for each of the options associated with the group::
    server.start(app, conf.bind_port, conf.bind_host, conf)
    self.connection = kombu.connection.BrokerConnection(
        hostname=conf.rabbit.host,
        port=conf.rabbit.port,
        ...)
Option values may reference other values using PEP 292 string substitution::
    opts = [
        cfg.StrOpt('state_path',
                   default=os.path.join(os.path.dirname(__file__), '../'),
                   help='Top-level directory for maintaining nova state'),
        cfg.StrOpt('sqlite_db',
                   default='nova.sqlite',
                   help='file name for sqlite'),
        cfg.StrOpt('sql_connection',
                   default='sqlite:///$state_path/$sqlite_db',
                   help='connection string for sql database'),
    ]
Note that interpolation can be avoided by using '$$'.
For command line utilities that dispatch to other command line utilities, the
disable_interspersed_args() method is available. If this this method is called,
then parsing e.g.::
  script --verbose cmd --debug /tmp/mything
will no longer return::
  ['cmd', '/tmp/mything']
as the leftover arguments, but will instead return::
  ['cmd', '--debug', '/tmp/mything']
i.e. argument parsing is stopped at the first non-option argument.
Options may be declared as required so that an error is raised if the user
does not supply a value for the option.
Options may be declared as secret so that their values are not leaked into
log files:
     opts = [
        cfg.StrOpt('s3_store_access_key', secret=True),
        cfg.StrOpt('s3_store_secret_key', secret=True),
        ...
     ]
This module also contains a global instance of the CommonConfigOpts class
in order to support a common usage pattern in OpenStack:
  from openstack.common import cfg
  opts = [
    cfg.StrOpt('bind_host' default='0.0.0.0'),
    cfg.IntOpt('bind_port', default=9292),
  ]
  CONF = cfg.CONF
  CONF.register_opts(opts)
  def start(server, app):
      server.start(app, CONF.bind_port, CONF.bind_host)
"""
import collections
import copy
import functools
import glob
import optparse
import os
import string
import sys
from nova.openstack.common import iniparser
class Error(Exception):
    """Base class for cfg exceptions."""
    def __init__(self, msg=None):
        self.msg = msg
    def __str__(self):
        return self.msg
class ArgsAlreadyParsedError(Error):
    """Raised if a CLI opt is registered after parsing."""
    def __str__(self):
        ret = "arguments already parsed"
        if self.msg:
            ret += ": " + self.msg
        return ret
class NoSuchOptError(Error, AttributeError):
    """Raised if an opt which doesn't exist is referenced."""
    def __init__(self, opt_name, group=None):
        self.opt_name = opt_name
        self.group = group
    def __str__(self):
        if self.group is None:
            return "no such option: %s" % self.opt_name
        else:
            return "no such option in group %s: %s" % (self.group.name,
                                                       self.opt_name)
class NoSuchGroupError(Error):
    """Raised if a group which doesn't exist is referenced."""
    def __init__(self, group_name):
        self.group_name = group_name
    def __str__(self):
        return "no such group: %s" % self.group_name
class DuplicateOptError(Error):
    """Raised if multiple opts with the same name are registered."""
    def __init__(self, opt_name):
        self.opt_name = opt_name
    def __str__(self):
        return "duplicate option: %s" % self.opt_name
class RequiredOptError(Error):
    """Raised if an option is required but no value is supplied by the user."""
    def __init__(self, opt_name, group=None):
        self.opt_name = opt_name
        self.group = group
    def __str__(self):
        if self.group is None:
            return "value required for option: %s" % self.opt_name
        else:
            return "value required for option: %s.%s" % (self.group.name,
                                                         self.opt_name)
class TemplateSubstitutionError(Error):
    """Raised if an error occurs substituting a variable in an opt value."""
    def __str__(self):
        return "template substitution error: %s" % self.msg
class ConfigFilesNotFoundError(Error):
    """Raised if one or more config files are not found."""
    def __init__(self, config_files):
        self.config_files = config_files
    def __str__(self):
        return ('Failed to read some config files: %s' %
                string.join(self.config_files, ','))
class ConfigFileParseError(Error):
    """Raised if there is an error parsing a config file."""
    def __init__(self, config_file, msg):
        self.config_file = config_file
        self.msg = msg
    def __str__(self):
        return 'Failed to parse %s: %s' % (self.config_file, self.msg)
class ConfigFileValueError(Error):
    """Raised if a config file value does not match its opt type."""
    pass
def _get_config_dirs(project=None):
    """Return a list of directors where config files may be located.
    :param project: an optional project name
    If a project is specified, following directories are returned::
      ~/.${project}/
      ~/
      /etc/${project}/
      /etc/
    Otherwise, these directories::
      ~/
      /etc/
    """
    fix_path = lambda p: os.path.abspath(os.path.expanduser(p))#获得p目录的绝对路径
    #os.path.join()是将两个参数用“/”连接起来,如~/.nova
    #if project else None,如果project为空,那么就将列表中的这一项置为None,在return时,会用filter过滤掉这个None项
    cfg_dirs = [
        fix_path(os.path.join('~', '.' + project)) if project else None,
        fix_path('~'),
        os.path.join('/etc', project) if project else None,
        '/etc'
    ]
    return filter(bool, cfg_dirs)
def _search_dirs(dirs, basename, extension=""):
    """Search a list of directories for a given filename.
    Iterator over the supplied directories, returning the first file
    found with the supplied name and extension.
    :param dirs: a list of directories
    :param basename: the filename, e.g. 'glance-api'
    :param extension: the file extension, e.g. '.conf'
    :returns: the path to a matching file, or None
    """
    #给定一个文件名和一组可能包含这个文件的目录,在这些目录中搜索这个文件所在的目录
    #返回找到的第一个文件所在的目录,返回的是一个相对路径,但包含文件名
    #e.g. /etc/nova/nova.conf
    for d in dirs:
        path = os.path.join(d, '%s%s' % (basename, extension))
        if os.path.exists(path):
            return path
def find_config_files(project=None, prog=None, extension='.conf'):
    """Return a list of default configuration files.
    :param project: an optional project name
    :param prog: the program name, defaulting to the basename of sys.argv[0]
    :param extension: the type of the config file
    We default to two config files: [${project}.conf, ${prog}.conf]
    And we look for those config files in the following directories::
      ~/.${project}/
      ~/
      /etc/${project}/
      /etc/
    We return an absolute path for (at most) one of each the default config
    files, for the topmost directory it exists in.
    For example, if project=foo, prog=bar and /etc/foo/foo.conf, /etc/bar.conf
    and ~/.foo/bar.conf all exist, then we return ['/etc/foo/foo.conf',
    '~/.foo/bar.conf']
    If no project name is supplied, we only look for ${prog.conf}.
    """
    if prog is None:
        prog = os.path.basename(sys.argv[0])
    cfg_dirs = _get_config_dirs(project)
    config_files = []
    if project:
        config_files.append(_search_dirs(cfg_dirs, project, extension))
    config_files.append(_search_dirs(cfg_dirs, prog, extension))
    #返回的是包含文件名在内的所有配置文件所在的目录的一个列表
    return filter(bool, config_files)
def _is_opt_registered(opts, opt):
    """Check whether an opt with the same name is already registered.
    The same opt may be registered multiple times, with only the first
    registration having any effect. However, it is an error to attempt
    to register a different opt with the same name.
    :param opts: the set of opts already registered
    :param opt: the opt to be registered
    :returns: True if the opt was previously registered, False otherwise
    :raises: DuplicateOptError if a naming conflict is detected
    """
    if opt.dest in opts:
        if opts[opt.dest]['opt'] is not opt:
            raise DuplicateOptError(opt.name)
        return True
    else:
        return False
# Opt的一个对象,代表了一个选项,即一个option
# 可调用里面的_add_to_cli()方法,将这个选项添加到一个组或者是一个解析器中。
class Opt(object):
    """Base class for all configuration options.
    An Opt object has no public methods, but has a number of public string
    properties:
      name:
        the name of the option, which may include hyphens
      dest:
        the (hyphen-less) ConfigOpts property which contains the option value
      short:
        a single character CLI option name
      default:
        the default value of the option
      metavar:
        the name shown as the argument to a CLI option in --help output
      help:
        an string explaining how the options value is used
    """
    multi = False
    def __init__(self, name, dest=None, short=None, default=None,
                 metavar=None, help=None, secret=False, required=False,
                 deprecated_name=None):
        """Construct an Opt object.
        The only required parameter is the option's name. However, it is
        common to also supply a default and help string for all options.
        :param name: the option's name
        :param dest: the name of the corresponding ConfigOpts property
        :param short: a single character CLI option name
        :param default: the default value of the option
        :param metavar: the option argument to show in --help
        :param help: an explanation of how the option is used
        :param secret: true iff the value should be obfuscated in log output
        :param required: true iff a value must be supplied for this option
        :param deprecated_name: deprecated name option.  Acts like an alias
        """
        self.name = name
        if dest is None:
            self.dest = self.name.replace('-', '_')
        else:
            self.dest = dest
        self.short = short
        self.default = default
        self.metavar = metavar
        self.help = help
        self.secret = secret
        self.required = required
        if deprecated_name is not None:
            self.deprecated_name = deprecated_name.replace('-', '_')
        else:
            self.deprecated_name = None
    def _get_from_config_parser(self, cparser, section):
        """Retrieves the option value from a MultiConfigParser object.
        This is the method ConfigOpts uses to look up the option value from
        config files. Most opt types override this method in order to perform
        type appropriate conversion of the returned value.
        :param cparser: a ConfigParser object
        :param section: a section name
        """
        return self._cparser_get_with_deprecated(cparser, section)
    #从所有配置文件生成的sections中,找section下的dest或者是deprecated_name所对应的值
    def _cparser_get_with_deprecated(self, cparser, section):
        """If cannot find option as dest try deprecated_name alias."""
        if self.deprecated_name is not None:
            return cparser.get(section, [self.dest, self.deprecated_name])
        return cparser.get(section, [self.dest])
    #这个函数的最终结果是给组(OptionGroup)或者是解析器(parser)添加一个选项(option)
    #如果指定了组,那么就添加到组中,否则添加到解析器(parser)中
    #container,即OptionContainer,是OptionGroup和OptionParser的父类
    def _add_to_cli(self, parser, group=None):
        """Makes the option available in the command line interface.
        This is the method ConfigOpts uses to add the opt to the CLI interface
        as appropriate for the opt type. Some opt types may extend this method,
        others may just extend the helper methods it uses.
        :param parser: the CLI option parser
        :param group: an optional OptGroup object
        """
        container = self._get_optparse_container(parser, group)
        kwargs = self._get_optparse_kwargs(group)#kwargs={
                                                 #    'dest':group.name+'_'+self.dest
                                                 #    'metavar':self.metavar
                                                 #    'help':self.help
                                                 #}
        prefix = self._get_optparse_prefix('', group)#这里prefix为: group.name+'-'
        self._add_to_optparse(container, self.name, self.short, kwargs, prefix,
                              self.deprecated_name)
    def _add_to_optparse(self, container, name, short, kwargs, prefix='',
                         deprecated_name=None):
        """Add an option to an optparse parser or group.
        :param container: an optparse.OptionContainer object
        :param name: the opt name
        :param short: the short opt name
        :param kwargs: the keyword arguments for add_option()
        :param prefix: an optional prefix to prepend to the opt name
        :raises: DuplicateOptError if a naming confict is detected
        """
        args = ['--' + prefix + name]
        if short:
            args += ['-' + short]
        if deprecated_name:
            args += ['--' + prefix + deprecated_name]
        for a in args:
            if container.has_option(a):
                raise DuplicateOptError(a)
        container.add_option(*args, **kwargs)
    #group是一个OptGroup对象,这个函数的作用是获得OptGroup对象中的OptionGroup对象,
    #OptionGroup对象才是核心要操作的东西。
    def _get_optparse_container(self, parser, group):
        """Returns an optparse.OptionContainer.
        :param parser: an optparse.OptionParser
        :param group: an (optional) OptGroup object
        :returns: an optparse.OptionGroup if a group is given, else the parser
        """
        #如果要给选项建立一个组的话,那么就新生成一个OptionGroup对象,或者是用已经建好的对象
        #如果不给选项建立组的话,那么就直接返回这个解析器,把选项直接放到这个解析器里
        #此处parser作为参数传递过去的作用有2个:
        #1. 若没有指定组,则直接返回这个parser
        #2. 若指定了组,在获得这个组中的OptionGroup对象的时候,如果这个对象还没有创建,则创建的时候要
        #   用到parser,如果已经创建,则直接返回创建好的这个OptionGroup对象,parser就没有用到了。
        if group is not None:
            return group._get_optparse_group(parser)
        else:
            return parser
    #主要是在dest前加上组名,然后重新组成一个kwargs字典,返回
    #字典中就包含三项内容:dest, metavar, help
    def _get_optparse_kwargs(self, group, **kwargs):
        """Build a dict of keyword arguments for optparse's add_option().
        Most opt types extend this method to customize the behaviour of the
        options added to optparse.
        :param group: an optional group
        :param kwargs: optional keyword arguments to add to
        :returns: a dict of keyword arguments
        """
        dest = self.dest
        if group is not None:
            dest = group.name + '_' + dest
        kwargs.update({'dest': dest,
                       'metavar': self.metavar,
                       'help': self.help, })
        return kwargs
    def _get_optparse_prefix(self, prefix, group):
        """Build a prefix for the CLI option name, if required.
        CLI options in a group are prefixed with the group's name in order
        to avoid conflicts between similarly named options in different
        groups.
        :param prefix: an existing prefix to append to (e.g. 'no' or '')
        :param group: an optional OptGroup object
        :returns: a CLI option prefix including the group name, if appropriate
        """
        if group is not None:
            return group.name + '-' + prefix
        else:
            return prefix
class StrOpt(Opt):
    """
    String opts do not have their values transformed and are returned as
    str objects.
    """
    pass
class BoolOpt(Opt):
    """
    Bool opts are set to True or False on the command line using --optname or
    --noopttname respectively.
    In config files, boolean values are case insensitive and can be set using
    1/0, yes/no, true/false or on/off.
    """
    _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
                       '0': False, 'no': False, 'false': False, 'off': False}
    def _get_from_config_parser(self, cparser, section):
        """Retrieve the opt value as a boolean from ConfigParser."""
        def convert_bool(v):
            value = self._boolean_states.get(v.lower())
            if value is None:
                raise ValueError('Unexpected boolean value %r' % v)
            return value
        return [convert_bool(v) for v in
                self._cparser_get_with_deprecated(cparser, section)]
    def _add_to_cli(self, parser, group=None):
        """Extends the base class method to add the --nooptname option."""
        super(BoolOpt, self)._add_to_cli(parser, group)
        self._add_inverse_to_optparse(parser, group)
    def _add_inverse_to_optparse(self, parser, group):
        """Add the --nooptname option to the option parser."""
        container = self._get_optparse_container(parser, group)
        kwargs = self._get_optparse_kwargs(group, action='store_false')
        prefix = self._get_optparse_prefix('no', group)
        kwargs["help"] = "The inverse of --" + self.name
        self._add_to_optparse(container, self.name, None, kwargs, prefix,
                              self.deprecated_name)
    def _get_optparse_kwargs(self, group, action='store_true', **kwargs):
        """Extends the base optparse keyword dict for boolean options."""
        return super(BoolOpt,
                     self)._get_optparse_kwargs(group, action=action, **kwargs)
class IntOpt(Opt):
    """Int opt values are converted to integers using the int() builtin."""
    def _get_from_config_parser(self, cparser, section):
        """Retrieve the opt value as a integer from ConfigParser."""
        return [int(v) for v in self._cparser_get_w
推荐阅读
  • 如何实现织梦DedeCms全站伪静态
    本文介绍了如何通过修改织梦DedeCms源代码来实现全站伪静态,以提高管理和SEO效果。全站伪静态可以避免重复URL的问题,同时通过使用mod_rewrite伪静态模块和.htaccess正则表达式,可以更好地适应搜索引擎的需求。文章还提到了一些相关的技术和工具,如Ubuntu、qt编程、tomcat端口、爬虫、php request根目录等。 ... [详细]
  • 一、Hadoop来历Hadoop的思想来源于Google在做搜索引擎的时候出现一个很大的问题就是这么多网页我如何才能以最快的速度来搜索到,由于这个问题Google发明 ... [详细]
  • 本文介绍了在Win10上安装WinPythonHadoop的详细步骤,包括安装Python环境、安装JDK8、安装pyspark、安装Hadoop和Spark、设置环境变量、下载winutils.exe等。同时提醒注意Hadoop版本与pyspark版本的一致性,并建议重启电脑以确保安装成功。 ... [详细]
  • mac php错误日志配置方法及错误级别修改
    本文介绍了在mac环境下配置php错误日志的方法,包括修改php.ini文件和httpd.conf文件的操作步骤。同时还介绍了如何修改错误级别,以及相应的错误级别参考链接。 ... [详细]
  • 一句话解决高并发的核心原则
    本文介绍了解决高并发的核心原则,即将用户访问请求尽量往前推,避免访问CDN、静态服务器、动态服务器、数据库和存储,从而实现高性能、高并发、高可扩展的网站架构。同时提到了Google的成功案例,以及适用于千万级别PV站和亿级PV网站的架构层次。 ... [详细]
  • 安装mysqlclient失败解决办法
    本文介绍了在MAC系统中,使用django使用mysql数据库报错的解决办法。通过源码安装mysqlclient或将mysql_config添加到系统环境变量中,可以解决安装mysqlclient失败的问题。同时,还介绍了查看mysql安装路径和使配置文件生效的方法。 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • 本文介绍了Python版Protobuf的安装和使用方法,包括版本选择、编译配置、示例代码等内容。通过学习本教程,您将了解如何在Python中使用Protobuf进行数据序列化和反序列化操作,以及相关的注意事项和技巧。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • Java String与StringBuffer的区别及其应用场景
    本文主要介绍了Java中String和StringBuffer的区别,String是不可变的,而StringBuffer是可变的。StringBuffer在进行字符串处理时不生成新的对象,内存使用上要优于String类。因此,在需要频繁对字符串进行修改的情况下,使用StringBuffer更加适合。同时,文章还介绍了String和StringBuffer的应用场景。 ... [详细]
  • Oracle分析函数first_value()和last_value()的用法及原理
    本文介绍了Oracle分析函数first_value()和last_value()的用法和原理,以及在查询销售记录日期和部门中的应用。通过示例和解释,详细说明了first_value()和last_value()的功能和不同之处。同时,对于last_value()的结果出现不一样的情况进行了解释,并提供了理解last_value()默认统计范围的方法。该文对于使用Oracle分析函数的开发人员和数据库管理员具有参考价值。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 本文介绍了在Mac上配置环境变量,实现Python3的命令行调用的步骤。首先通过官网下载或使用brew安装Python3,并找到安装路径。然后将该路径添加到环境变量中,可以通过编辑.bash_profile文件或执行source命令来实现。配置完成后,即可在命令行中直接调用Python3。 ... [详细]
  • 本文介绍了在MacOS系统上安装MySQL的步骤,并详细说明了如何设置MySQL服务的开机启动和如何修改MySQL的密码。通过下载MySQL的macos版本并按照提示一步一步安装,在系统偏好设置中可以找到MySQL的图标进行设置。同时,还介绍了通过终端命令来修改MySQL的密码的具体操作步骤。 ... [详细]
author-avatar
手机用户2502886695
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有