本文整理汇总了Python中six.moves.configparser.ConfigParser.read_file方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigParser.read_file方法的具体用法?Python ConfigParser.read_file怎么用?Python ConfigParser.read_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.configparser.ConfigParser
的用法示例。
在下文中一共展示了ConfigParser.read_file方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_config
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import read_file [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
示例2: INIReader
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import read_file [as 别名]
class INIReader(object):
"""ConfigParser wrapper able to cast value when reading INI options."""
# Helper casters
cast_boolean = casts.Boolean()
cast_dict = casts.Dict()
cast_list = casts.List()
cast_logging_level = casts.LoggingLevel()
cast_tuple = casts.Tuple()
cast_webdriver_desired_capabilities = casts.WebdriverDesiredCapabilities()
def __init__(self, path):
self.config_parser = ConfigParser()
with open(path) as handler:
self.config_parser.readfp(handler)
if sys.version_info[0] < 3:
# ConfigParser.readfp is deprecated on Python3, read_file
# replaces it
self.config_parser.readfp(handler)
else:
self.config_parser.read_file(handler)
def get(self, section, option, default=None, cast=None):
"""Read an option from a section of a INI file.
The default value will return if the look up option is not available.
The value will be cast using a callable if specified otherwise a string
will be returned.
:param section: Section to look for.
:param option: Option to look for.
:param default: The value that should be used if the option is not
defined.
:param cast: If provided the value will be cast using the cast
provided.
"""
try:
value = self.config_parser.get(section, option)
if cast is not None:
if cast is bool:
value = self.cast_boolean(value)
elif cast is dict:
value = self.cast_dict(value)
elif cast is list:
value = self.cast_list(value)
elif cast is tuple:
value = self.cast_tuple(value)
else:
value = cast(value)
except (NoSectionError, NoOptionError):
value = default
return value
def has_section(self, section):
"""Check if section is available."""
return self.config_parser.has_section(section)
示例3: _parseINI
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import read_file [as 别名]
def _parseINI(text):
from six.moves.configparser import ConfigParser
from six.moves import cStringIO
parser = ConfigParser()
try:
parser.read_file(cStringIO(text))
except AttributeError: # Python 2
parser.readfp(cStringIO(text))
return parser
示例4: put_ini
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import read_file [as 别名]
def put_ini(self, text):
"""
"""
context = self.context
parser = ConfigParser()
try:
parser.read_file(cStringIO(text))
except AttributeError: # Python 2
parser.readfp(cStringIO(text))
for option, value in parser.defaults().items():
prop_type = context.getPropertyType(option)
if prop_type is None:
context._setProperty(option, value, 'string')
else:
context._updateProperty(option, value)
示例5: _load_config
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import read_file [as 别名]
def _load_config(no_cfgfile=False):
config = ConfigParser()
config.optionxform = str # make it preserve case
# defaults
if not six.PY3:
config.readfp(BytesIO(_DEFAULT_CONFIG))
else:
config.read_file(StringIO(_DEFAULT_CONFIG))
# update from config file
if not no_cfgfile:
config.read(os.path.join(_STASH_ROOT, f) for f in _STASH_CONFIG_FILES)
return config
示例6: _makeInstance
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import read_file [as 别名]
def _makeInstance(self, id, portal_type, subdir, import_context):
context = self.context
subdir = '%s/%s' % (subdir, id)
properties = self.read_data_file(import_context, '.properties',
subdir)
tool = getUtility(ITypesTool)
try:
tool.constructContent(portal_type, context, id)
except ValueError: # invalid type
return None
content = context._getOb(id)
if properties is not None:
if '[DEFAULT]' not in properties:
try:
adp = FolderishDAVAwareFileAdapter
adp(content).import_(import_context, subdir)
return content
except (AttributeError, MethodNotAllowed):
# Fall through to old implemenatation below
pass
lines = properties.splitlines()
stream = StringIO('\n'.join(lines))
parser = ConfigParser(defaults={'title': '',
'description': 'NONE'})
try:
parser.read_file(stream)
except AttributeError: # Python 2
parser.readfp(stream)
title = parser.get('DEFAULT', 'title')
description = parser.get('DEFAULT', 'description')
content.setTitle(title)
content.setDescription(description)
return content
示例7: handle
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import read_file [as 别名]
def handle(self, *args, **options):
# type: (*Any, **Any) -> None
config_file = os.path.join(os.environ["HOME"], ".zuliprc")
if not os.path.exists(config_file):
raise RuntimeError("No ~/.zuliprc found")
config = ConfigParser()
with open(config_file, 'r') as f:
# Apparently, six.moves.configparser.ConfigParser is not
# consistent between Python 2 and 3!
if hasattr(config, 'read_file'):
config.read_file(f, config_file)
else:
config.readfp(f, config_file)
api_key = config.get("api", "key")
email = config.get("api", "email")
try:
realm = get_realm("zulip")
user_profile = get_user(email, realm)
user_profile.api_key = api_key
user_profile.save(update_fields=["api_key"])
except UserProfile.DoesNotExist:
print("User %s does not exist; not syncing API key" % (email,))