本文整理汇总了Python中six.moves.configparser.SafeConfigParser.has_section方法的典型用法代码示例。如果您正苦于以下问题:Python SafeConfigParser.has_section方法的具体用法?Python SafeConfigParser.has_section怎么用?Python SafeConfigParser.has_section使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.configparser.SafeConfigParser
的用法示例。
在下文中一共展示了SafeConfigParser.has_section方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import has_section [as 别名]
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
示例2: getManifest
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import has_section [as 别名]
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
示例3: Config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import has_section [as 别名]
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 {}
示例4: logging_config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import has_section [as 别名]
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)
示例5: _update_settings_from_file
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import has_section [as 别名]
def _update_settings_from_file(section, settings):
tries = 0
current_directory = os.path.normpath(os.getcwd())
config_file = None
while current_directory and tries < MAX_CONFIG_SEARCH_DEPTH:
potential_path = os.path.join(current_directory, 'setup.cfg')
if os.path.exists(potential_path):
config_file = potential_path
break
new_directory = os.path.split(current_directory)[0]
if current_directory == new_directory:
break
current_directory = new_directory
tries += 1
if config_file and os.path.exists(config_file):
with open(config_file, 'rU') as fp:
config = SafeConfigParser()
config.readfp(fp)
if config.has_section('tool:multilint'):
settings.update(sanitize(config.items('tool:multilint')))
示例6: get_scrapycfg_targets
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import has_section [as 别名]
def get_scrapycfg_targets(cfgfiles=None):
cfg = SafeConfigParser()
cfg.read(cfgfiles or [])
baset = dict(cfg.items('deploy')) if cfg.has_section('deploy') else {}
targets = {}
targets['default'] = baset
for x in cfg.sections():
if x.startswith('deploy:'):
t = baset.copy()
t.update(cfg.items(x))
targets[x[7:]] = t
for tname, t in list(targets.items()):
try:
int(t.get('project', 0))
except ValueError:
# Don't import non-numeric project IDs, and also throw away the
# URL and credentials associated with these projects (since the
# project ID does not belong to SH, neither do the endpoint or the
# auth information)
del targets[tname]
if t.get('url', "").endswith('scrapyd/'):
t['url'] = t['url'][:-8]
targets.setdefault('default', {})
return targets
示例7: onDiscovery
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import has_section [as 别名]
def onDiscovery(self, theme, settings, dependenciesSettings):
res = queryResourceDirectory(THEME_RESOURCE_NAME, theme)
if res is None:
return
directoryName = 'views'
if 'directory' in settings:
directoryName = settings['directory']
if res.isDirectory(directoryName):
viewsDir = res[directoryName]
layer = getattr(schemata, theme, None)
if 'layer' in settings:
layerName = settings['layer']
try:
layer = resolve(layerName)
except (ImportError, AttributeError):
logger.warn("Could not import %s" % layerName)
return
viewConfig = SafeConfigParser()
if viewsDir.isFile(VIEW_CONFIG_FILENAME):
fp = viewsDir.openFile(VIEW_CONFIG_FILENAME)
try:
viewConfig.readfp(fp)
finally:
try:
fp.close()
except AttributeError:
pass
views = []
configurationMachine = ConfigurationMachine()
path = viewsDir.directory
for filename in os.listdir(path):
if not filename.lower().endswith(EXTENSION):
continue
name = viewName = filename[:-3]
permission = 'zope2.View'
for_ = Interface
class_ = None
template = os.path.join(path, filename)
menu = {}
# Read override options from views.cfg if applicable
if viewConfig.has_section(name):
if viewConfig.has_option(name, 'name'):
viewName = viewConfig.get(name, 'name')
if viewConfig.has_option(name, 'permission'):
permission = viewConfig.get(name, 'permission')
if viewConfig.has_option(name, 'for'):
forStr = viewConfig.get(name, 'for')
if forStr != "*":
for_ = resolve(forStr)
if viewConfig.has_option(name, 'class'):
class_ = resolve(viewConfig.get(name, 'class'))
if viewConfig.has_option(name, 'menu'):
menu = dict(
title=viewConfig.get(name, 'menu'),
menu=getattr(
zope.browsermenu.metaconfigure.menus,
"plone_displayviews",
),
)
Products.Five.browser.metaconfigure.page(
configurationMachine,
name=viewName,
permission=permission,
for_=for_,
layer=layer,
template=template,
class_=class_,
**menu
)
views.append(name)
if len(views) > 0:
configurationMachine.execute_actions()
self.registered[theme] = views
示例8: PackageConfigHandler
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import has_section [as 别名]
class PackageConfigHandler(object):
"""
Manager class for packages files for tracking installation of modules
"""
def __init__(self):
# noinspection PyUnresolvedReferences
from six.moves.configparser import SafeConfigParser
self.package_cfg = os.path.expanduser('~/Documents/site-packages/.pypi_packages')
if not os.path.isfile(self.package_cfg):
print('Creating package file')
with open(self.package_cfg, 'w') as outs:
outs.close()
self.parser = SafeConfigParser()
self.parser.read(self.package_cfg)
def save(self):
with open(self.package_cfg, 'w') as outs:
self.parser.write(outs)
def add_module(self, pkg_info):
"""
:param pkg_info: A dict that has name, url, version, summary
:return:
"""
if not self.parser.has_section(pkg_info['name']):
self.parser.add_section(pkg_info['name'])
self.parser.set(pkg_info['name'], 'url', pkg_info['url'])
self.parser.set(pkg_info['name'], 'version', pkg_info['version'])
self.parser.set(pkg_info['name'], 'summary', pkg_info['summary'])
self.parser.set(pkg_info['name'], 'files', pkg_info['files'])
self.parser.set(pkg_info['name'], 'dependency', pkg_info['dependency'])
self.save()
def list_modules(self):
return [module for module in self.parser.sections()]
def module_exists(self, name):
return self.parser.has_section(name)
def get_info(self, name):
if self.parser.has_section(name):
tbl = {}
for opt, value in self.parser.items(name):
tbl[opt] = value
return tbl
def remove_module(self, name):
self.parser.remove_section(name)
self.save()
def get_files_installed(self, section_name):
if self.parser.has_option(section_name, 'files'):
files = self.parser.get(section_name, 'files').strip()
return files.split(',')
else:
return None
def get_dependencies(self, section_name):
if self.parser.has_option(section_name, 'dependency'):
dependencies = self.parser.get(section_name, 'dependency').strip()
return set(dependencies.split(',')) if dependencies != '' else set()
else:
return None
def get_all_dependencies(self, exclude_module=()):
all_dependencies = set()
for section_name in self.parser.sections():
if section_name not in exclude_module and self.parser.has_option(section_name, 'dependency'):
dependencies = self.parser.get(section_name, 'dependency').strip()
if dependencies != '':
for dep in dependencies.split(','):
all_dependencies.add(dep)
return all_dependencies
示例9: Config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import has_section [as 别名]
class Config(object):
"""
Manages the configuration file
"""
def __init__(self):
"""
DEFAULT VALUES
"""
self._basescript = None
self.recentvaults = []
self.pwlength = 10
self.search_notes = False
self.search_passwd = False
self.alphabet = "abcdefghikmnopqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWXYZ_"
self.avoid_bigrams = "cl mn nm nn rn vv VV"
self._fname = self.get_config_filename()
self._parser = SafeConfigParser()
if os.path.exists(self._fname):
self._parser.read(self._fname)
if not self._parser.has_section("base"):
self._parser.add_section("base")
for num in range(10):
if (not self._parser.has_option("base", "recentvaults" + str(num))):
break
self.recentvaults.append(self._parser.get("base", "recentvaults" + str(num)))
if self._parser.has_option("base", "pwlength"):
self.pwlength = int(self._parser.get("base", "pwlength"))
if self._parser.has_option("base", "search_notes"):
if self._parser.get("base", "search_notes") == "True":
self.search_notes = True
if self._parser.has_option("base", "search_passwd"):
if self._parser.get("base", "search_passwd") == "True":
self.search_passwd = True
if self._parser.has_option("base", "alphabet"):
self.alphabet = self._parser.get("base", "alphabet")
if self._parser.has_option("base", "avoid_bigrams"):
self.avoid_bigrams = self._parser.get("base", "avoid_bigrams")
if not os.path.exists(self._fname):
self.save()
def set_basescript(self, basescript):
self._basescript = basescript
def get_basescript(self):
return self._basescript
def save(self):
if (not os.path.exists(os.path.dirname(self._fname))):
os.mkdir(os.path.dirname(self._fname))
# remove duplicates and trim to 10 items
_saved_recentvaults = []
for item in self.recentvaults:
if item in _saved_recentvaults:
continue
self._parser.set("base", "recentvaults" + str(len(_saved_recentvaults)), item)
_saved_recentvaults.append(item)
if (len(_saved_recentvaults) >= 10):
break
self._parser.set("base", "pwlength", str(self.pwlength))
self._parser.set("base", "search_notes", str(self.search_notes))
self._parser.set("base", "search_passwd", str(self.search_passwd))
self._parser.set("base", "alphabet", str(self.alphabet))
self._parser.set("base", "avoid_bigrams", str(self.avoid_bigrams))
filehandle = open(self._fname, 'w')
self._parser.write(filehandle)
filehandle.close()
@staticmethod
def get_config_filename():
"""
Returns the full filename of the config file
"""
base_fname = "loxodo"
# On Mac OS X, config files go to ~/Library/Application Support/foo/
if platform.system() == "Darwin":
base_path = os.path.join(os.path.expanduser("~"), "Library", "Application Support")
if os.path.isdir(base_path):
return os.path.join(base_path, base_fname, base_fname + ".ini")
# On Microsoft Windows, config files go to $APPDATA/foo/
if platform.system() in ("Windows", "Microsoft"):
if ("APPDATA" in os.environ):
base_path = os.environ["APPDATA"]
if os.path.isdir(base_path):
return os.path.join(base_path, base_fname, base_fname + ".ini")
# Allow config directory override as per freedesktop.org XDG Base Directory Specification
#.........这里部分代码省略.........
示例10: IniConfigLoader
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import has_section [as 别名]
class IniConfigLoader(object):
"""This config loader transforms a traditional INI file into
a Montague Standard Format dictionary. It is compatible with
most but not all PasteDeploy files."""
def __init__(self, path):
self.path = path
self._data = self._read()
self._config = self._process()
def _read(self):
# We need to keep the parser around so the logging conversion can use it.
path_defaults = {
'here': os.path.dirname(self.path),
'__file__': self.path,
}
self._parser = SafeConfigParser()
self._parser.read(self.path)
self._globals = self._parser.defaults()
data = {}
for section in self._parser.sections():
section_data = data.setdefault(section, {})
for option in self._parser.options(section):
if option in self._globals:
continue
try:
section_data[option] = self._parser.get(section, option, vars=path_defaults)
except InterpolationError:
section_data[option] = self._parser.get(section, option, raw=True)
return data
def _process(self):
orig = self._data
config = {}
for key in six.iterkeys(orig):
if ':' in key:
scheme, name = key.split(':', 1)
kind_config = config.setdefault(SCHEMEMAP[scheme], {})
kind_config[name] = orig[key]
else:
config[key] = orig[key]
config['globals'] = {
'here': os.path.dirname(self.path),
'__file__': self.path,
}
for key, value in six.iteritems(self._globals):
config['globals'][key] = value
apps = config.setdefault('application', {})
filters = config.setdefault('filter', {})
generated_filter_count = 0
filter_apps = config.pop('filter-app', {})
for name, filter_app in six.iteritems(filter_apps):
use = filter_app.pop('next')
generated_filter_count += 1
filter_name = '_montague_filter_{0}'.format(generated_filter_count)
apps[name] = {'use': use, 'filter-with': filter_name}
filters[filter_name] = filter_app
pipelines = config.pop('pipeline', {})
for name, pipeline in six.iteritems(pipelines):
items = pipeline['pipeline'].split()
pipeline_app = items[-1]
pipeline_filters = items[:-1]
pipeline_filters.reverse()
apps[name] = {'use': pipeline_app}
last_item = apps[name]
for count, use_filter in enumerate(pipeline_filters, start=1):
filter_name = '_montague_pipeline_{0}_filter_{1}'.format(name, count)
filters[filter_name] = {'use': use_filter}
last_item['filter-with'] = filter_name
last_item = filters[filter_name]
if all([self._parser.has_section(section_name) for section_name in LOGGING_SECTIONS]):
loggers = convert_loggers(self._parser)
handlers = convert_handlers(self._parser)
formatters = convert_formatters(self._parser)
config['logging'] = {'main': combine(loggers, handlers, formatters)}
for key in MSF_KEYS:
config.setdefault(key, {})
return config
def config(self):
return self._config
def app_config(self, name):
# This method isn't actually necessary, since montague can extract
# the config information from the MSF dict returned by .config()
# but it's a nice example of how to do it.
if name in self._config['application']:
constructor = LoadableConfig.app
local_config = self._config['application'][name]
elif name in self._config['composite']:
constructor = LoadableConfig.composite
local_config = self._config['composite'][name]
else:
raise KeyError
return constructor(
name=name, config=local_config, global_config=self._config['globals'])
def server_config(self, name):
#.........这里部分代码省略.........