当前位置: 首页>>代码示例>>Python>>正文


Python configparser.SafeConfigParser类代码示例

本文整理汇总了Python中six.moves.configparser.SafeConfigParser的典型用法代码示例。如果您正苦于以下问题:Python SafeConfigParser类的具体用法?Python SafeConfigParser怎么用?Python SafeConfigParser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了SafeConfigParser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: from_sections

 def from_sections(cls, sections):
     config = SafeConfigParser()
     for section, keyvalues in sections.items():
         config.add_section(section)
         for key, value in keyvalues.items():
             config.set(section, key, value)
     return cls(config)
开发者ID:pignacio,项目名称:issue2branch,代码行数:7,代码来源:config.py

示例2: load_from_config

def load_from_config(config_file, args, values):
    """
    Load config from user's home folder, and load into config object. If values are given during runtime that conflict
    with values in config file, the config file values are overwritten.

    :param config_file: Name of an existing config file
    :param args: Array of values containing argument names from main
    :param values: Array of values containing values from arguments from main
    :return: key/value pairs of args/values
    """
    # TODO: Handle args not existing in user config file and passed args
    config = dict()
    if config_file:
        load_config = os.path.join(BASE_CONFIG_DIR, config_file)
        if os.path.exists(load_config):
            parser = SafeConfigParser()
            parser.read(load_config)
            for _var in CONFIG_VARS:
                config[_var['var']] = parser.get('settings', _var['var'])

    items = values.items()
    for k, v in items:
        if k in args and v is not None:
            config[k] = v

    for _var in CONFIG_VARS:
        if _var['var'] in args and values[_var['var']] is not None:
            config[_var['var']] = values[_var['var']]
        if _var["var"] not in config:
            click.echo(_var['error'])

    return namedtuple('GenericDict', config.keys())(**config)
开发者ID:enrico2828,项目名称:Stash2Jira,代码行数:32,代码来源:cli.py

示例3: read

    def read(self):
        """Override base class version to avoid parsing error with the first
        'RANDFILE = ...' part of the openssl file.  Also, reformat _sections
        to allow for the style of SSL config files where section headings can
        have spaces either side of the brackets e.g.
        [ sectionName ]

        and comments can occur on the same line as an option e.g.
        option = blah # This is option blah

        Reformat _sections to """
        try:
            config_file = open(self._filePath)
            fileTxt = config_file.read()
        except Exception as e:
            raise OpenSSLConfigError('Reading OpenSSL config file "%s": %s' %
                                                    (self._filePath, e))

        idx = re.search('\[\s*\w*\s*\]', fileTxt).span()[0]
        config_file.seek(idx)
        SafeConfigParser.readfp(self, config_file)

        # Filter section names and remove comments from options
        for section, val in list(self._sections.items()):
            newSection = section
            self._sections[newSection.strip()] = \
                                    dict([(opt, self._filtOptVal(optVal))
                                          for opt, optVal in list(val.items())])
            del self._sections[section]

        self._set_required_dn_params()
开发者ID:cedadev,项目名称:MyProxyClient,代码行数:31,代码来源:openssl.py

示例4: from_config

    def from_config(cls, path, **kwargs):
        """
        Create a LastFM instance from a config file in the following format:

            [lastfm]
            api_key = myapikey
            api_secret = myapisecret
            username = thesquelched
            password = plaintext_password

            # Can be 'password' or 'hashed_password'
            auth_method = password

        You can also override config values with keyword arguments.
        """
        config = SafeConfigParser()
        config.add_section('lastfm')
        config.read(os.path.expanduser(os.path.expandvars(path)))

        return LastFM(
            cls._getoption(config, kwargs, 'api_key'),
            cls._getoption(config, kwargs, 'api_secret'),
            username=cls._getoption(config, kwargs, 'username', None),
            password=cls._getoption(config, kwargs, 'password', None),
            auth_method=cls._getoption(config, kwargs, 'auth_method', None),
            session_key=cls._getoption(config, kwargs, 'session_key', None),
            url=cls._getoption(config, kwargs, 'url', None),
        )
开发者ID:KokaKiwi,项目名称:pylastfm,代码行数:28,代码来源:client.py

示例5: ConfigHelper

class ConfigHelper(object):
    NONE_VALUE = 'None'
    DEFAULT_HOST = "127.0.0.1"
    DEFAULT_PORT = 5696
    DEFAULT_CERTFILE = os.path.normpath(os.path.join(
        FILE_PATH, '../demos/certs/server.crt'))
    DEFAULT_KEYFILE = os.path.normpath(os.path.join(
        FILE_PATH, '../demos/certs/server.key'))
    DEFAULT_CA_CERTS = os.path.normpath(os.path.join(
        FILE_PATH, '../demos/certs/server.crt'))
    DEFAULT_SSL_VERSION = 'PROTOCOL_SSLv23'
    DEFAULT_USERNAME = None
    DEFAULT_PASSWORD = None

    def __init__(self):
        self.logger = logging.getLogger(__name__)

        self.conf = SafeConfigParser()
        if self.conf.read(CONFIG_FILE):
            self.logger.debug("Using config file at {0}".format(CONFIG_FILE))
        else:
            self.logger.warning(
                "Config file {0} not found".format(CONFIG_FILE))

    def get_valid_value(self, direct_value, config_section,
                        config_option_name, default_value):
        """Returns a value that can be used as a parameter in client or
        server. If a direct_value is given, that value will be returned
        instead of the value from the config file. If the appropriate config
        file option is not found, the default_value is returned.

        :param direct_value: represents a direct value that should be used.
                             supercedes values from config files
        :param config_section: which section of the config file to use
        :param config_option_name: name of config option value
        :param default_value: default value to be used if other options not
                              found
        :returns: a value that can be used as a parameter
        """
        ARG_MSG = "Using given value '{0}' for {1}"
        CONF_MSG = "Using value '{0}' from configuration file {1} for {2}"
        DEFAULT_MSG = "Using default value '{0}' for {1}"
        if direct_value:
            return_value = direct_value
            self.logger.debug(ARG_MSG.format(direct_value, config_option_name))
        else:
            try:
                return_value = self.conf.get(config_section,
                                             config_option_name)
                self.logger.debug(CONF_MSG.format(return_value,
                                                  CONFIG_FILE,
                                                  config_option_name))
            except:
                return_value = default_value
                self.logger.debug(DEFAULT_MSG.format(default_value,
                                                     config_option_name))
        if return_value == self.NONE_VALUE:
            return None
        else:
            return return_value
开发者ID:cactorium,项目名称:PyKMIP,代码行数:60,代码来源:config_helper.py

示例6: read_config_file

    def read_config_file(path):
        config = SafeConfigParser()
        cfp = open(path, 'r')
        config.readfp(cfp)
        cfp.close()

        return config
开发者ID:loowho11,项目名称:opencafe,代码行数:7,代码来源:managers.py

示例7: _init_config_parser

    def _init_config_parser(self, sections=None):
        parser = SafeConfigParser(allow_no_value=True)
        if sections:
            for section in sections:
                parser.add_section(section)
                for key, value in sections[section].items():
                    parser.set(section, key,
                               self._value_converter.to_strings(value))

        return parser
开发者ID:HoratiusTang,项目名称:trove,代码行数:10,代码来源:stream_codecs.py

示例8: Config

class Config(object):

    def __init__(self):
        self.config = SafeConfigParser()
        self.name = ''

    def parse(self, fname, override):
        if override:
            override = [x for x in csv.reader(
                ' '.join(override).split(','), delimiter='.')]

        logger.info('Reading configuration file: {}'.format(fname))
        if not os.path.isfile(fname):
            logger.interrupt('File doesn\'t exist: {}'.format(fname))
        self.config.optionxform = str
        self.config.read(fname)
        for section, option, value in override:
            if not self.config.has_section(section):
                self.config.add_section(section)
            self.config.set(section, option, value)

        basename = os.path.basename(fname)
        self.name = os.path.splitext(basename)[0]

    @safe
    def _get_options_as_dict(self, section):
        if section in self.config.sections():
            return {p: v for p, v in self.config.items(section)}
        else:
            return {}
开发者ID:mahesh152,项目名称:perfrunner,代码行数:30,代码来源:settings.py

示例9: getManifest

def getManifest(fp, format, defaults=None):
    """Read the manifest from the given open file pointer according to the
    given ManifestFormat. Pass a dict as ``defaults`` to override the defaults
    from the manifest format.
    """

    if defaults is None:
        defaults = format.defaults

    parser = SafeConfigParser()
    if six.PY2:
        parser.readfp(fp)
    else:
        data = fp.read()
        if isinstance(data, six.binary_type):
            data = data.decode()
        parser.read_string(data)

    results = {}
    for key in format.keys:
        if parser.has_option(format.resourceType, key):
            results[key] = parser.get(format.resourceType, key)
        else:
            results[key] = defaults.get(key, None)

    for key in format.parameterSections:
        sectionName = "%s:%s" % (format.resourceType, key,)
        if parser.has_section(sectionName):
            results[key] = dict(parser.items(sectionName))
        else:
            results[key] = {}

    return results
开发者ID:plone,项目名称:plone.resource,代码行数:33,代码来源:manifest.py

示例10: load

def load(f):
    p = SafeConfigParser()
    p.read(f)
    if not p.has_section('oauth2'):
        p.add_section('oauth2')
    if not p.has_section('oauth2-state'):
        p.add_section('oauth2-state')
    return p
开发者ID:moriyoshi,项目名称:docker-dev-mta-postfix,代码行数:8,代码来源:oauth2.py

示例11: __init__

 def __init__(self, values=None, extra_sources=()):
     if values is None:
         sources = self._getsources()
         default_config = get_data(__package__, 'default_scrapyd.conf').decode('utf8')
         self.cp = SafeConfigParser()
         self.cp.readfp(StringIO(default_config))
         self.cp.read(sources)
         for fp in extra_sources:
             self.cp.readfp(fp)
     else:
         self.cp = SafeConfigParser(values)
         self.cp.add_section(self.SECTION)
开发者ID:cleocn,项目名称:scrapyd,代码行数:12,代码来源:config.py

示例12: logging_config

 def logging_config(self, name):
     if name != 'main':
         raise KeyError
     parser = SafeConfigParser()
     parser.read(self.path)
     for section_name in ('loggers', 'handlers', 'formatters'):
         if not parser.has_section(section_name):
             raise KeyError
     loggers = convert_loggers(parser)
     handlers = convert_handlers(parser)
     formatters = convert_formatters(parser)
     return combine(loggers, handlers, formatters)
开发者ID:inklesspen,项目名称:montague_pastedeploy,代码行数:12,代码来源:ini.py

示例13: read_config_file

def read_config_file():
    if not os.path.isfile(config_file_path):
        download_config_file()

    config = SafeConfigParser()
    config.optionxform = str
    list_of_successfully_parsed_files = config.read(config_file_path)
    if config_file_path not in list_of_successfully_parsed_files:
        raise Exception(
            'Could not read {0} succesfully.'.format(config_file_path)
        )
    return config
开发者ID:fact-project,项目名称:shifthelper,代码行数:12,代码来源:__init__.py

示例14: init_ini_file

def init_ini_file(file=args.ini_file):
    cp=SafeConfigParser()
    fp=open(file)
    cp.optionxform = str
    cp.readfp(fp)
    fp.close()

    cp.set('condor','lalsuite-install',lalinf_prefix)
    cp.set('analysis','engine',args.engine)
    cp.remove_option('analysis','nparallel')

    return cp
开发者ID:lscsoft,项目名称:lalsuite,代码行数:12,代码来源:lalinference_review_test.py

示例15: Config

class Config(object):
    """A ConfigParser wrapper to support defaults when calling instance
    methods, and also tied to a single section"""

    SECTION = 'scrapyd'

    def __init__(self, values=None, extra_sources=()):
        if values is None:
            sources = self._getsources()
            default_config = get_data(__package__, 'default_scrapyd.conf').decode('utf8')
            self.cp = SafeConfigParser()
            self.cp.readfp(StringIO(default_config))
            self.cp.read(sources)
            for fp in extra_sources:
                self.cp.readfp(fp)
        else:
            self.cp = SafeConfigParser(values)
            self.cp.add_section(self.SECTION)

    def _getsources(self):
        sources = ['/etc/scrapyd/scrapyd.conf', r'c:\scrapyd\scrapyd.conf']
        sources += sorted(glob.glob('/etc/scrapyd/conf.d/*'))
        sources += ['scrapyd.conf']
        sources += [expanduser('~/.scrapyd.conf')]
        scrapy_cfg = closest_scrapy_cfg()
        if scrapy_cfg:
            sources.append(scrapy_cfg)
        return sources

    def _getany(self, method, option, default):
        try:
            return method(self.SECTION, option)
        except (NoSectionError, NoOptionError):
            if default is not None:
                return default
            raise

    def get(self, option, default=None):
        return self._getany(self.cp.get, option, default)

    def getint(self, option, default=None):
        return self._getany(self.cp.getint, option, default)

    def getfloat(self, option, default=None):
        return self._getany(self.cp.getfloat, option, default)

    def getboolean(self, option, default=None):
        return self._getany(self.cp.getboolean, option, default)

    def items(self, section, default=None):
        try:
            return self.cp.items(section)
        except (NoSectionError, NoOptionError):
            if default is not None:
                return default
            raise
开发者ID:cleocn,项目名称:scrapyd,代码行数:56,代码来源:config.py


注:本文中的six.moves.configparser.SafeConfigParser类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。