本文整理汇总了Python中ConfigParser.ConfigParser.items方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigParser.items方法的具体用法?Python ConfigParser.items怎么用?Python ConfigParser.items使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConfigParser.ConfigParser
的用法示例。
在下文中一共展示了ConfigParser.items方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def __init__(self, config_filename):
locale.setlocale(locale.LC_ALL, '')
assert os.path.isfile(config_filename), "Config file not found"
local_config_parser = ConfigParser()
local_config_parser.read(config_filename)
product_info_filename = local_config_parser.get("Config", "info_produtos")
self._printer_name = local_config_parser.get("Config", "impressora")
assert os.path.isfile(product_info_filename), "Product info file not found"
# Set barcode filename
self._barcode_filename = os.path.join(
os.path.dirname(product_info_filename),
"barcode"
)
cfg_parser = ConfigParser()
cfg_parser.read(product_info_filename)
self._primary_categories = dict(cfg_parser.items(self.PRIMARY_CATEGORY_SEC))
self._secondary_categories = dict(cfg_parser.items(self.SECONDARY_CATEGORY_SEC))
if cfg_parser.has_section(self.PRICE_SEC):
self.price_list = []
for opt in sorted(cfg_parser.options(self.PRICE_SEC)):
self.price_list.append(cfg_parser.getfloat(self.PRICE_SEC, opt))
else:
self.price_list = [1.7, 2.21]
self._label_header = cfg_parser.get("Label", "header").replace("\\n","\n")
self._label_template = cfg_parser.get("Label", "label")
self._labels_per_file = 30
self._product_unity = "pç"
self._category_on_label = cfg_parser.getint("Geral", "cat_etiqueta")
示例2: _convert
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def _convert(self):
from ConfigParser import ConfigParser
cp=ConfigParser()
cp.read(self.filename)
for section in [ 'main', 'default' ]:
if cp.has_section( section ):
for key, val in cp.items(section):
key = key.lower().replace('_', '')
self.repo_cfg[ "%s.%s" % (section, key) ] = val
for section in filter( lambda n: n.startswith('store '),
cp.sections() ):
for key, val in cp.items(section):
key = key.lower().replace('_', '')
self.repo_cfg[ "store.%s.%s" % (section[6:].strip(' "'), key) ] = val
if not self.repo_cfg.has_key( "store.%s.enabled" % section[6:].strip(' "') ):
self.repo_cfg[ "store.%s.enabled" % section[6:].strip(' "') ] = "true"
tmpfile = "%s.%d.%s" % ( self.filename, os.getpid(), ".tmp" )
try:
self.save( tmpfile )
os.rename( tmpfile, self.filename )
except:
os.unlink( tmpfile )
raise
示例3: _reload_options
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def _reload_options(self):
try:
self.ctime = os.stat(self.cpath).st_mtime
cfg = ConfigParser()
cfg.read(self.cpath)
except OSError:
raise ConfigFileNotFoundError(self.cpath, source="default config")
sections = cfg.sections()
if len(sections) < 1:
raise ImproperConfigFileError(self.cpath, _(u"%s should have at least one section" % self.cpath))
options = Struct()
options.main = mainsect = dict(cfg.items("main"))
options.sections = sections
## if not(options.has_key("module") ^ options.has_key("path")):
## raise ImproperConfigFileError(self.cpath,
## _(u"%s should have a ``module`` or ``path`` option, but not both" % self.cpath))
if not (mainsect.has_key("module") ^ mainsect.has_key("path")):
raise ImproperConfigFileError(
self.cpath, _(u"%s should have a ``module`` or ``path`` option, but not both" % self.cpath)
)
for sectname in sections[1:]:
options[sectname] = dict(cfg.items(sectname))
self.hotplug = mainsect.get("hotplug", False)
self.module = mainsect.get("module", None)
self.mpath = mainsect.get("path", "")
self.class_ = mainsect.get("class", "")
return options
示例4: _get_args
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def _get_args():
try: # py2
from ConfigParser import ConfigParser
except ImportError: # py3
from configparser import ConfigParser
args = docopt.docopt(__doc__,
version=seltest.__version__,
argv=sys.argv[1:])
config_path = args['--config'] or _find_config()
config = {}
profile_config = {}
if config_path:
config_path = _expand_path(config_path)
# allow_no_value so we can write `-v`, not `-v=True`
cp = ConfigParser(allow_no_value=True)
cp.read(config_path)
# this allows -v to mean -v=True, not -v=None
config = dict((key, True if value is None else value)
for key, value in cp.items('default'))
profile_name = args['--config-profile']
if profile_name:
profile_config = dict((key, True if value is None else value)
for key, value in cp.items(profile_name))
config = _merge_config_dicts(config, DEFAULTS)
config = _merge_config_dicts(profile_config, config)
config = _merge_config_dicts(args, config)
return config
示例5: read_file
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def read_file(self):
self.validate_config()
config = ConfigParser()
config.read(self.hosts_file)
sections = config.sections()
host_store = {}
self.logger.debug("Extracting all List sections if mandatory, and store "
"it in host_store as a List with key value as list section_name")
for section_name in self.list_sections:
if section_name in sections:
count = config.getint(section_name, TOTAL_KEY)
try:
prefix = config.get(section_name, PREFIX_KEY)
except NoOptionError:
prefix = section_name
try:
postfix = config.get(section_name, POSTFIX_KEY)
except NoOptionError:
postfix = ''
host_store[section_name] = []
for index in range(count):
index = index + 1
child_section = '%s%s%s' % (prefix, index, postfix)
items = config.items(child_section)
host_store[section_name].append(dict(items))
sections.remove(child_section)
sections.remove(section_name)
self.logger.debug("Extracting all other configurations from file and "
"store it as a dictionary with key value as section_name")
for section_name in sections:
items = config.items(section_name)
host_store[section_name] = dict(items)
return host_store
示例6: read_cfg
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def read_cfg(floc, cfg_proc=process_cfg):
"""
Reads the given configuration file, returning a dict with the converted values supplemented by default values.
:param floc: The location of the file to read.
:param cfg_proc: The processor to use for the raw configuration values. Uses default values when the raw
value is missing.
:return: A dict of the processed configuration file's data.
"""
config = ConfigParser()
try:
good_files = config.read(floc)
except ParsingError as e:
raise InvalidDataError(e)
if not good_files:
raise IOError('Could not read file {}'.format(floc))
main_proc = cfg_proc(dict(config.items(MAIN_SEC)), DEF_CFG_VALS, REQ_KEYS, int_list=False)
# Check that there is a least one subsection, or this script won't do anything. Check that all sections given
# are expected or alert user that a given section is ignored (thus catches types, etc.)
no_work_to_do = True
for section in config.sections():
if section in SECTIONS:
if section in SUB_SECTIONS:
if len(config.items(section)) > 0:
no_work_to_do = False
else:
warning("Found section '{}', which will be ignored. Expected section names are: {}"
.format(section, ", ".join(SECTIONS)))
if no_work_to_do:
warning("No filtering will be applied as no criteria were found for the expected subsections ({})."
"".format(", ".join(SUB_SECTIONS)))
for section in [MAX_SEC, MIN_SEC]:
main_proc[section] = check_vals(config, section)
main_proc[BIN_SEC] = get_bin_data(config, BIN_SEC)
return main_proc
示例7: parse_image_build_config
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def parse_image_build_config(self, config_file_name):
# Logic taken from koji.cli.koji.handle_image_build.
# Unable to re-use koji's code because "cli" is not
# a package of koji and this logic is intermingled
# with CLI specific instructions.
args = []
opts = {}
config = ConfigParser()
config.readfp(self.get_default_image_build_conf())
config.read(config_file_name)
if self.architectures:
config.set('image-build', 'arches', ','.join(self.architectures))
elif self.architecture:
config.set('image-build', 'arches', self.architecture)
# else just use what was provided by the user in image-build.conf
config_str = StringIO()
config.write(config_str)
self.log.debug('Image Build Config: \n%s', config_str.getvalue())
image_name = None
section = 'image-build'
for option in ('name', 'version', 'arches', 'target', 'install_tree'):
value = config.get(section, option)
if not value:
raise ValueError('{} cannot be empty'.format(option))
if option == 'arches':
value = [arch for arch in value.split(',') if arch]
elif option == 'name':
image_name = value
args.append(value)
config.remove_option(section, option)
for option, value in config.items(section):
if option in ('repo', 'format'):
value = [v for v in value.split(',') if v]
elif option in ('disk_size'):
value = int(value)
opts[option] = value
section = 'ova-options'
if config.has_section(section):
ova = []
for k, v in config.items(section):
ova.append('{}={}'.format(k, v))
opts['ova_option'] = ova
section = 'factory-parameters'
if config.has_section(section):
factory = []
for option, value in config.items(section):
factory.append((option, value))
opts['factory_parameter'] = factory
return image_name, args, {'opts': opts}
示例8: _create_configs_from_file
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def _create_configs_from_file(filename, cluster_config_dir, wildcards):
configurations = ConfigParser(allow_no_value=True)
configurations.read(filename)
for config_file in configurations.sections():
logger.info("Updating %s...", config_file)
# For XML configuration files, run things through XmlConfiguration.
if config_file.endswith('.xml'):
XmlConfiguration(
{item[0]: item[1].format(**wildcards)
for item in configurations.items(config_file)}
).write_to_file(join(cluster_config_dir, config_file))
# For everything else, recognize whether a line in the configuration should simply be
# appended to the bottom of a file or processed in some way. The presence of +++ will
# lead to the evaluation of the following string through the end of the line.
else:
lines = []
for item in configurations.items(config_file):
if item[0].startswith('+++'):
command = item[0].lstrip('+ ').format(**wildcards)
# Yes, we use eval here. This is potentially dangerous, but intention.
lines.append(str(eval(command))) # pylint: disable=eval-used
elif item[0] == "body":
lines.append(item[1].format(**wildcards))
else:
lines.append(item[0].format(**wildcards))
with open(join(cluster_config_dir, config_file), 'w') as conf:
conf.write("".join(["{0}\n".format(line) for line in lines]))
示例9: config_from_file
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def config_from_file(config_file):
global config
global template_dirs
global template_loader
# Read configuration
here = os.path.abspath('.')
confp = ConfigParser(defaults={'here': here})
confp.read(config_file)
for sec in ('stats', 'checkers', 'alerts', 'mailer'):
config[sec] = dict(confp.items(sec))
# Setup template loader
template_dirs = [
os.path.abspath('./templates')]
template_loader.search_path.extend(template_dirs)
# Load and register additional checkers
for name, cls_name in confp.items('checkers'):
if name != 'here':
cls = _load_checker(name, cls_name)
logging.info('Loaded checker %s: %r', name, cls)
return
示例10: __init__
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def __init__(self):
conf = ConfigParser()
conf.read('conf.ini')
self.log_url = 'https://xueqiu.com/user/login'
self.log_data = dict(conf.items('account'))
self.header = dict(conf.items('header'))
示例11: parse_config
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def parse_config(configs):
"""
:type configs list
:rtype: ConfigParser
"""
conf = ConfigParser()
all_configs = []
while len(configs) > 0:
all_configs += configs
files = []
for mask in configs:
for f in glob.glob(mask):
if os.path.isfile(f):
files.append(f)
conf.read(files)
configs = []
if conf.has_option(DEFAULT_SECTION, "include"):
configs = list(set(re.split(r'\s+', conf.get(DEFAULT_SECTION, "include"))) - set(all_configs))
for section in conf.sections():
for k, v in conf.items(DEFAULT_SECTION):
if not conf.has_option(section, k):
conf.set(section, k, v)
for k, v in conf.items(section):
v = re.sub(r'^\s*"|"\s*$', '', v) # remove quotes
conf.set(section, k, v)
conf.remove_section(DEFAULT_SECTION)
if not conf.sections():
usage("No sections found in config files " + ", ".join(all_configs))
return conf
示例12: Playlist
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
class Playlist(object):
def __init__(self, location):
dir = os.path.expanduser(os.path.dirname(location))
if not os.path.exists(dir):
os.makedirs(dir)
self._config = ConfigParser()
self._config.optionxform = str
self._file = os.path.expanduser(location)
if os.path.exists(self._file):
self._config.read(self._file)
else:
self._config.add_section('Playlist')
self.save()
def save(self):
self._config.write(open(self._file, 'wb'))
def append(self, item):
self._config.set('Playlist', *item)
self.save()
def remove(self, option):
self._config.remove_option('Playlist', option)
self.save()
def __getitem__(self, item):
return self._config.items('Playlist')[item]
def __iter__(self):
return iter(self._config.items('Playlist'))
示例13: parse_config
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def parse_config(self, config_filename):
if not config_filename:
config_filename = os.path.join(os.path.dirname(__file__), 'configs', 'default.ini')
if not os.path.exists(config_filename):
config_filename = os.path.join(os.path.dirname(__file__), 'configs', config_filename)
if not os.path.exists(config_filename):
self.logger.error('Could not open configuration file %s', config_filename)
sys.exit(1)
config = ConfigParser()
config.read(config_filename)
self.logger.info('Loaded configuration file: %s', config_filename)
# Parse configuration
for section in config.sections():
if section == 'FakeNet':
self.fakenet_config = dict(config.items(section))
elif section == 'Diverter':
self.diverter_config = dict(config.items(section))
elif config.getboolean(section, 'enabled'):
self.listeners_config[section] = dict(config.items(section))
示例14: get_app_info
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def get_app_info(app_dir, app):
app_info = {'app_key': app}
dev_dir = join(app_dir, app, DEVELOP_DIR)
if isdir(dev_dir) and exists(join(dev_dir, CER_FILE)) \
and exists(join(dev_dir, KEY_FILE)):
# 读配置文件
conf = join(dev_dir, CONF_FILE)
conf_dict = {}
if exists(conf):
config = ConfigParser()
config.read(conf)
conf_dict = dict(config.items('apnsagent'))
app_info['develop'] = {'cer_file': join(dev_dir, CER_FILE),
'key_file': join(dev_dir, KEY_FILE),
'config': conf_dict}
pro_dir = join(app_dir, app, PRODUCTION_DIR)
if isdir(pro_dir) and exists(join(pro_dir, CER_FILE)) \
and exists(join(pro_dir, KEY_FILE)):
conf = join(pro_dir, CONF_FILE)
log.debug('config file: %s' % conf)
conf_dict = {}
if exists(conf):
log.debug('load config file')
config = ConfigParser()
config.read(conf)
conf_dict = dict(config.items('apnsagent'))
log.debug('config content %s' % conf_dict)
app_info['production'] = {'cer_file': join(pro_dir, CER_FILE),
'key_file': join(pro_dir, KEY_FILE),
'config': conf_dict}
return app_info
示例15: read_config_file
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import items [as 别名]
def read_config_file(filename):
"""Return Settings instance built from contents of ``filename`` file."""
parser = ConfigParser()
parser.read(filename)
settings = Settings()
core_section = 'macman'
default_section = 'default'
# Handle core configuration.
if parser.has_section(core_section):
section = core_section
for option in ['directory']:
if parser.has_option(section, option):
setattr(settings, option, parser.get(section, option))
# Handle default configuration.
if parser.has_section(default_section):
section = settings.default
settings.default = dict(parser.items(section))
# Handle configuration of VMs.
special_sections = (core_section, default_section)
for section in parser.sections():
if section in special_sections:
continue
vm_id = section
settings.vms[vm_id] = dict(parser.items(section))
return settings