本文整理汇总了Python中six.moves.configparser.ConfigParser.sections方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigParser.sections方法的具体用法?Python ConfigParser.sections怎么用?Python ConfigParser.sections使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.configparser.ConfigParser
的用法示例。
在下文中一共展示了ConfigParser.sections方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: loadKeysConfig
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def loadKeysConfig(path=None):
"""Load keys config file.
If path is ``None``, a file named :any:`DEFAULT_KEYS_FILE` will be looked for in the config
directory.
:param path: path of the keyboard configuration file
"""
if path is None:
path = getConfigFilePath(DEFAULT_KEYS_FILE)
cfg = ConfigParser()
cfg.optionxform = str
cfg.read([path])
for category in cfg.sections():
for actionName in cfg.options(category):
keystr = cfg.get(category, actionName)
context = Qt.WidgetShortcut
if keystr.startswith('widget:'):
keystr = keystr.split(':', 1)[1]
elif keystr.startswith('window:'):
keystr = keystr.split(':', 1)[1]
context = Qt.WindowShortcut
elif keystr.startswith('children:'):
keystr = keystr.split(':', 1)[1]
context = Qt.WidgetWithChildrenShortcut
elif keystr.startswith('application:'):
keystr = keystr.split(':', 1)[1]
context = Qt.ApplicationShortcut
qks = QKeySequence(keystr)
registerActionShortcut(category, actionName, qks, context)
示例2: _load_ec_as_default_policy
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def _load_ec_as_default_policy(proxy_conf_file, swift_conf_file, **kwargs):
"""
Override swift.conf [storage-policy:0] section to use a 2+1 EC policy.
:param proxy_conf_file: Source proxy conf filename
:param swift_conf_file: Source swift conf filename
:returns: Tuple of paths to the proxy conf file and swift conf file to use
"""
_debug('Setting configuration for default EC policy')
conf = ConfigParser()
conf.read(swift_conf_file)
# remove existing policy sections that came with swift.conf-sample
for section in list(conf.sections()):
if section.startswith('storage-policy'):
conf.remove_section(section)
# add new policy 0 section for an EC policy
conf.add_section('storage-policy:0')
ec_policy_spec = {
'name': 'ec-test',
'policy_type': 'erasure_coding',
'ec_type': 'liberasurecode_rs_vand',
'ec_num_data_fragments': 2,
'ec_num_parity_fragments': 1,
'ec_object_segment_size': 1048576,
'default': True
}
for k, v in ec_policy_spec.items():
conf.set('storage-policy:0', k, str(v))
with open(swift_conf_file, 'w') as fp:
conf.write(fp)
return proxy_conf_file, swift_conf_file
示例3: get_ic_factor
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def get_ic_factor(self, det):
# storing ic_factor in preferences causing issues
# ic_factor stored in detectors.cfg
p = os.path.join(paths.spectrometer_dir, 'detectors.cfg')
# factors=None
ic = 1, 0
if os.path.isfile(p):
c = ConfigParser()
c.read(p)
det = det.lower()
for si in c.sections():
if si.lower() == det:
v, e = 1, 0
if c.has_option(si, 'ic_factor'):
v = c.getfloat(si, 'ic_factor')
if c.has_option(si, 'ic_factor_err'):
e = c.getfloat(si, 'ic_factor_err')
ic = v, e
break
else:
self.debug('no detector file {}. cannot retrieve ic_factor'.format(p))
r = ufloat(*ic)
return r
示例4: get_config
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def get_config(p):
"""Read a config file.
:return: dict of ('section.option', value) pairs.
"""
cfg = {}
parser = ConfigParser()
if hasattr(parser, 'read_file'):
parser.read_file(Path(p).open(encoding='utf8'))
else: # pragma: no cover
assert PY2
# The `read_file` method is not available on ConfigParser in py2.7!
parser.readfp(Path(p).open(encoding='utf8'))
for section in parser.sections():
getters = {
'int': partial(parser.getint, section),
'boolean': partial(parser.getboolean, section),
'float': partial(parser.getfloat, section),
'list': lambda option: parser.get(section, option).split(),
}
default = partial(parser.get, section)
for option in parser.options(section):
type_ = option.rpartition('_')[2] if '_' in option else None
value = getters.get(type_, default)(option)
cfg['{0}.{1}'.format(section, option)] = value
return cfg
示例5: build_cli_examples
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def build_cli_examples(_):
logger = logging.getLogger('cli-examples')
clidir = os.path.join(SPHINX_DIR, 'cli')
exini = os.path.join(clidir, 'examples.ini')
exdir = os.path.join(clidir, 'examples')
if not os.path.isdir(exdir):
os.makedirs(exdir)
config = ConfigParser()
config.read(exini)
rsts = []
for sect in config.sections():
rst, cmd = _build_cli_example(config, sect, exdir, logger)
if cmd:
logger.info('[cli] running example {0!r}'.format(sect))
logger.debug('[cli] $ {0}'.format(cmd))
subprocess.check_call(cmd, shell=True)
logger.debug('[cli] wrote {0}'.format(cmd.split()[-1]))
rsts.append(rst)
with open(os.path.join(exdir, 'examples.rst'), 'w') as f:
f.write('.. toctree::\n :glob:\n\n')
for rst in rsts:
f.write(' {0}\n'.format(rst[len(SPHINX_DIR):]))
示例6: handleApps
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def handleApps(self, **kwargs):
l10nbuilds = urlopen(
'https://raw.githubusercontent.com/Pike/master-ball/'
'master/l10n-master/l10nbuilds.ini')
cp = ConfigParser()
cp.readfp(l10nbuilds)
for section in cp.sections():
self.stdout.write(section + '\n')
self.handleSection(section, dict(cp.items(section)))
示例7: get_configuration_dict
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def get_configuration_dict(configuration=None, value_types=None):
"""
Parse the configuration files
Parameters
----------
configuration : str or list, optional
A configuration file or list of configuration files to parse,
defaults to the deploy_default.conf file in the package and
deploy.conf in the current working directory.
value_types : dict, optional
Dictionary containing classes to apply to specific items
Returns
-------
dict
Configuration dictionary
"""
if not value_types: # pragma: no cover
value_types = config_types()
if configuration is None or configuration is '': # pragma: no cover
configuration = [
# Config file that is part of the package
# PACKAGE_DEFAULT_CONFIG,
# Any deploy.conf files in the current directory
'deploy.conf'
]
config = ConfigParser()
# Set the config defaults
try:
config.read_string(config_defaults())
except AttributeError:
config.readfp(io.BytesIO(config_defaults()))
logger.debug('Working with default dict: %r', config_defaults())
config.read(configuration)
result_dict = {}
for section in config.sections():
result_dict[section] = {}
for key, val in config.items(section):
result_dict[section][key] = str_format_env(val)
config_update(result_dict)
if 'locations' not in result_dict.keys():
result_dict['locations'] = {}
result_dict['locations']['package_scripts'] = package_scripts_directory()
if not result_dict['global'].get('virtualenv_dir', None):
result_dict['global']['virtualenv_dir'] = \
default_virtualenv_directory()
cast_types(result_dict)
return result_dict
示例8: parse_config_file
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def parse_config_file(file_path):
config = ConfigParser()
config.read(file_path)
if 'batch_scoring' not in config.sections():
# We are return empty dict, because there is nothing in this file
# that related to arguments to batch scoring.
return {}
parsed_dict = dict(config.items('batch_scoring'))
return config_validator(parsed_dict)
示例9: _read
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def _read(self):
parser = ConfigParser()
parser.read(self.path)
self._globals = parser.defaults()
data = {}
for section in parser.sections():
section_data = data.setdefault(section, {})
for option in parser.options(section):
if option in self._globals:
continue
section_data[option] = parser.get(section, option)
return data
示例10: load
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def load(self):
schemes = [defaultScheme]
parser = ConfigParser()
parser.read(settings.DASHBOARD_CONF)
for option, default_value in defaultUIConfig.items():
if parser.has_option('ui', option):
try:
self.ui_config[option] = parser.getint('ui', option)
except ValueError:
self.ui_config[option] = parser.get('ui', option)
else:
self.ui_config[option] = default_value
if parser.has_option('ui', 'automatic_variants'):
self.ui_config['automatic_variants'] = parser.getboolean('ui', 'automatic_variants')
else:
self.ui_config['automatic_variants'] = True
self.ui_config['keyboard_shortcuts'] = defaultKeyboardShortcuts.copy()
if parser.has_section('keyboard-shortcuts'):
self.ui_config['keyboard_shortcuts'].update( parser.items('keyboard-shortcuts') )
for section in parser.sections():
if section in ('ui', 'keyboard-shortcuts'):
continue
scheme = parser.get(section, 'scheme')
fields = []
for match in fieldRegex.finditer(scheme):
field = match.group(1)
if parser.has_option(section, '%s.label' % field):
label = parser.get(section, '%s.label' % field)
else:
label = field
fields.append({
'name' : field,
'label' : label
})
schemes.append({
'name' : section,
'pattern' : scheme,
'fields' : fields,
})
self.schemes = schemes
示例11: read_test_ini
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def read_test_ini(file_dir=FILE_DIR, section="FacebookAuth"):
ini_file_path = os.path.join(file_dir, "test.ini")
ret = {}
if os.path.isfile(ini_file_path):
cp = ConfigParser()
cp.read(ini_file_path)
if section not in cp.sections():
raise EnvironmentError(
"Section '{0}' not in test.ini".format(section))
for arg in cp.options(section):
ret[arg] = cp.get(section, arg)
else:
raise EnvironmentError(
"File test.ini not existing in path '{0}'".format(FILE_DIR))
return ret
示例12: _get_retentions_from_storage_schemas
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def _get_retentions_from_storage_schemas(self, opts):
"""Parse storage-schemas.conf and returns all retentions."""
ret = []
config_parser = ConfigParser()
if not config_parser.read(opts.storage_schemas):
raise SystemExit(
"Error: Couldn't read config file: %s" % opts.storage_schemas
)
for section in config_parser.sections():
options = dict(config_parser.items(section))
retentions = options["retentions"].split(",")
archives = [carbon_util.parseRetentionDef(s) for s in retentions]
ret.append(bg_metric.Retention.from_carbon(archives))
return ret
示例13: load
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def load(self):
cfp = ConfigParser()
# p = os.path.join(paths.spectrometer_dir, 'config.cfg')
p = get_spectrometer_config_path()
cfp.read(p)
gs = []
for section in cfp.sections():
g = SpectrometerParametersGroup(name=section)
ps = []
for pp in cfp.options(section):
v = cfp.getfloat(section, pp)
ps.append(Parameter(name=pp, value=v))
g.parameters = ps
gs.append(g)
self.groups = gs
示例14: load_ini
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
def load_ini(self, ini_config):
"""
Read the provided ini contents arguments and merge
the data in the ini config into the config object.
ini_config is assumed to be a string of the ini file contents.
"""
parser = ConfigParser()
parser.readfp(StringIO(ini_config))
data = {
'linters': {},
'files': {},
'branches': {},
'fixers': {},
'review': {}
}
if parser.has_section('files'):
ignore = parser.get('files', 'ignore')
data['files']['ignore'] = newline_value(ignore)
if parser.has_section('branches'):
ignore = parser.get('branches', 'ignore')
data['branches']['ignore'] = comma_value(ignore)
linters = []
if parser.has_section('tools'):
linters = comma_value(parser.get('tools', 'linters'))
if parser.has_section('fixers'):
data['fixers'] = dict(parser.items('fixers'))
if parser.has_section('review'):
data['review'] = dict(parser.items('review'))
# Setup empty config sections
for linter in linters:
data['linters'][linter] = {}
for section in parser.sections():
if not section.startswith('tool_'):
continue
# Strip off tool_
linter = section[5:]
data['linters'][linter] = dict(parser.items(section))
self.update(data)
示例15: Namespaces
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import sections [as 别名]
class Namespaces(object):
r"""Helper for namespaces.
The config file would look like:
```
[carbon-relay]
pattern = carbon\.relay\.*
[carbon-cache]
pattern = carbon\.agents\.*
[carbon-aggregator]
pattern = carbon\.aggregator\.*
[prometheus]
pattern = prometheus\.*
```
"""
def __init__(self, filename=None):
"""Initializer."""
self.config = ConfigParser({}, collections.OrderedDict)
self.patterns = collections.OrderedDict()
if not filename:
self.patterns[re.compile(".*")] = "total"
self.config.add_section("total")
return
self.config.read(filename)
for section in self.config.sections():
pattern = re.compile(self.config.get(section, "pattern"))
self.patterns[pattern] = section
def lookup(self, metric_name):
"""Return the namespace corresponding to the metric."""
for pattern, section in self.patterns.items():
if pattern.match(metric_name):
return section, self.config.items(section)
return "none", None