本文整理汇总了Python中six.moves.configparser.RawConfigParser.readfp方法的典型用法代码示例。如果您正苦于以下问题:Python RawConfigParser.readfp方法的具体用法?Python RawConfigParser.readfp怎么用?Python RawConfigParser.readfp使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.configparser.RawConfigParser
的用法示例。
在下文中一共展示了RawConfigParser.readfp方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_providers
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import readfp [as 别名]
def update_providers(args, verbose=False):
filepath = args.data_dir.joinpath('references', 'bibtex', 'BIBFILES.ini')
p = RawConfigParser()
with io.open(filepath, encoding='utf-8-sig') as fp:
p.readfp(fp)
provider_map = get_map(Provider)
for section in p.sections():
sectname = section[:-4] if section.endswith('.bib') else section
id_ = slug(sectname)
attrs = {
'name': p.get(section, 'title'),
'description': p.get(section, 'description'),
'abbr': p.get(section, 'abbr'),
}
if id_ in provider_map:
provider = provider_map[id_]
for a in list(attrs):
before, after = getattr(provider, a), attrs[a]
if before == after:
del attrs[a]
else:
setattr(provider, a, after)
attrs[a] = (before, after)
if attrs:
args.log.info('updating provider %s %s' % (slug(id_), sorted(attrs)))
if verbose:
for a, (before, after) in attrs.items():
before, after = (' '.join(_.split()) for _ in (before, after))
if before != after:
args.log.info('%s\n%r\n%r' % (a, before, after))
else:
args.log.info('adding provider %s' % slug(id_))
DBSession.add(Provider(id=id_, **attrs))
示例2: update_library
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import readfp [as 别名]
def update_library(filename):
"""
Update units in current library from `filename`.
Parameters
----------
filename : string or file
Source of units configuration data.
"""
if isinstance(filename, basestring):
inp = open(filename, 'rU')
else:
inp = filename
try:
cfg = ConfigParser()
cfg.optionxform = _do_nothing
# New in Python 3.2: read_file() replaces readfp().
if sys.version_info >= (3, 2):
cfg.read_file(inp)
else:
cfg.readfp(inp)
_update_library(cfg)
finally:
inp.close()
示例3: import_library
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import readfp [as 别名]
def import_library(libfilepointer):
"""
Import a units library, replacing any existing definitions.
Parameters
----------
libfilepointer : file
new library file to work with
Returns
-------
ConfigParser
newly updated units library for the module
"""
global _UNIT_LIB
global _UNIT_CACHE
_UNIT_CACHE = {}
_UNIT_LIB = ConfigParser()
_UNIT_LIB.optionxform = _do_nothing
_UNIT_LIB.readfp(libfilepointer)
required_base_types = ['length', 'mass', 'time', 'temperature', 'angle']
_UNIT_LIB.base_names = list()
# used to is_angle() and other base type checking
_UNIT_LIB.base_types = dict()
_UNIT_LIB.unit_table = dict()
_UNIT_LIB.prefixes = dict()
_UNIT_LIB.help = list()
for prefix, factor in _UNIT_LIB.items('prefixes'):
factor, comma, comment = factor.partition(',')
_UNIT_LIB.prefixes[prefix] = float(factor)
base_list = [0] * len(_UNIT_LIB.items('base_units'))
for i, (unit_type, name) in enumerate(_UNIT_LIB.items('base_units')):
_UNIT_LIB.base_types[unit_type] = i
powers = list(base_list)
powers[i] = 1
# print '%20s'%unit_type, powers
# cant use add_unit because no base units exist yet
_new_unit(name, 1, powers)
_UNIT_LIB.base_names.append(name)
# test for required base types
missing = [utype for utype in required_base_types
if utype not in _UNIT_LIB.base_types]
if missing:
raise ValueError('Not all required base type were present in the'
' config file. missing: %s, at least %s required'
% (missing, required_base_types))
# Explicit unitless 'unit'.
_new_unit('unitless', 1, list(base_list))
_update_library(_UNIT_LIB)
return _UNIT_LIB
示例4: convert_config_to_tribler71
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import readfp [as 别名]
def convert_config_to_tribler71(current_config, state_dir=None):
"""
Convert the Config files libtribler.conf and tribler.conf to the newer triblerd.conf and cleanup the files
when we are done.
:param: current_config: the current config in which we merge the old config files.
:return: the newly edited TriblerConfig object with the old data inserted.
"""
state_dir = state_dir or TriblerConfig.get_default_state_dir()
libtribler_file_loc = os.path.join(state_dir, "libtribler.conf")
if os.path.exists(libtribler_file_loc):
libtribler_cfg = RawConfigParser()
libtribler_cfg.read(libtribler_file_loc)
current_config = add_libtribler_config(current_config, libtribler_cfg)
os.remove(libtribler_file_loc)
tribler_file_loc = os.path.join(state_dir, "tribler.conf")
if os.path.exists(tribler_file_loc):
tribler_cfg = RawConfigParser()
tribler_cfg.read(tribler_file_loc)
current_config = add_tribler_config(current_config, tribler_cfg)
os.remove(tribler_file_loc)
# We also have to update all existing downloads, in particular, rename the section 'downloadconfig' to
# 'download_defaults'.
for _, filename in enumerate(iglob(
os.path.join(state_dir, STATEDIR_DLPSTATE_DIR, '*.state'))):
download_cfg = RawConfigParser()
try:
with open(filename) as cfg_file:
download_cfg.readfp(cfg_file, filename=filename)
except MissingSectionHeaderError:
logger.error("Removing download state file %s since it appears to be corrupt", filename)
os.remove(filename)
try:
download_items = download_cfg.items("downloadconfig")
download_cfg.add_section("download_defaults")
for download_item in download_items:
download_cfg.set("download_defaults", download_item[0], download_item[1])
download_cfg.remove_section("downloadconfig")
with open(filename, "w") as output_config_file:
download_cfg.write(output_config_file)
except (NoSectionError, DuplicateSectionError):
# This item has already been converted
pass
return current_config
示例5: get_config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import readfp [as 别名]
def get_config(extra_locations=get_config_locations(), is_test=False):
config = RawConfigParser()
config.readfp(get_default_conf())
conf_files = config.read(extra_locations)
for conf_file in conf_files:
config.readfp(open(conf_file, 'r'))
# Not a huge fan of when developers think they're smarter than the
# end-users, but I'm calling it a special case for testing
is_travis = 'TRAVIS_BUILD_NUMBER' in os.environ
is_pytest = hasattr(sys, '_called_from_test')
if is_pytest or is_travis or is_test:
config.set('metrik', 'mongo_database', 'metrik-test')
return config
示例6: _parseFile
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import readfp [as 别名]
def _parseFile(self, cfgpath):
# add a starting section so it becomes INI format
try:
with open(cfgpath) as fp:
contents = fp.read()
except IOError:
LOGGER.error('cannot read %r', cfgpath, exc_info=True)
return None
fp = StringIO('[_ROOT_]\n%s' % contents)
cfg = RawConfigParser()
try:
cfg.readfp(fp, cfgpath)
except Error:
LOGGER.error('cannot parse %r', cfgpath, exc_info=True)
return None
return cfg
示例7: update_library
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import readfp [as 别名]
def update_library(filename):
"""
Update units in current library from `filename`, which must contain a
``units`` section.
filename: string or file
Source of units configuration data.
"""
if isinstance(filename, basestring):
inp = open(filename, 'rU')
else:
inp = filename
try:
cfg = ConfigParser()
cfg.optionxform = _do_nothing
cfg.readfp(inp)
_update_library(cfg)
finally:
inp.close()
示例8: configure
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import readfp [as 别名]
def configure(opts):
credential_path = os.path.join(os.path.expanduser("~"), ".carbonblack")
credential_file = os.path.join(credential_path, "credentials.protection")
print("Welcome to the CbAPI.")
if os.path.exists(credential_file):
print("An existing credential file exists at {0}.".format(credential_file))
resp = input("Do you want to continue and overwrite the existing configuration? [Y/N] ")
if resp.strip().upper() != "Y":
print("Exiting.")
return 1
if not os.path.exists(credential_path):
os.makedirs(credential_path, 0o700)
url = input("URL to the Cb Protection server [https://hostname]: ")
ssl_verify = None
while ssl_verify not in ["Y", "N"]:
ssl_verify = input("Use SSL/TLS certificate validation (answer 'N' if using self-signed certs) [Y/N]: ")
ssl_verify = ssl_verify.strip().upper()
if ssl_verify == "Y":
ssl_verify = True
else:
ssl_verify = False
token = input("API token: ")
config = RawConfigParser()
config.readfp(StringIO('[default]'))
config.set("default", "url", url)
config.set("default", "token", token)
config.set("default", "ssl_verify", ssl_verify)
with temp_umask(0):
with os.fdopen(os.open(credential_file, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, 0o600), 'w') as fp:
os.chmod(credential_file, 0o600)
config.write(fp)
print("Successfully wrote credentials to {0}.".format(credential_file))
示例9: ConfigParser
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import readfp [as 别名]
__all__ = ['ini', 'settings']
import os.path
from six.moves.configparser import RawConfigParser as ConfigParser
from .loader import Loader
HERE = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(HERE, '..', 'data')
DEFAULT_FILE = os.path.join(DATA_DIR, 'defaults.cfg')
ini = ConfigParser()
ini.optionxform = str # avoid .lower() method
with open(DEFAULT_FILE) as file:
ini.readfp(file)
ini.read(['/etc/meuh.cfg', os.path.expanduser('~/.meuh.cfg'), '.meuh.cfg'])
class Settings(object):
def __init__(self, ini, data_dir):
self.ini = ini
self.loader = Loader(data_dir)
self.fresh = False
def read(self, filename):
self.ini.read(filename)
self.fresh = False
def __getitem__(self, name):
return self.cached[name]
示例10: ConfigSettings
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import readfp [as 别名]
#.........这里部分代码省略.........
self.__delitem__(k)
def __init__(self):
self._config = RawConfigParser()
self._config.optionxform = str
self._settings = {}
self._sections = {}
self._finalized = False
self.loaded_files = set()
def load_file(self, filename):
self.load_files([filename])
def load_files(self, filenames):
"""Load a config from files specified by their paths.
Files are loaded in the order given. Subsequent files will overwrite
values from previous files. If a file does not exist, it will be
ignored.
"""
filtered = [f for f in filenames if os.path.exists(f)]
fps = [open(f, 'rt') for f in filtered]
self.load_fps(fps)
self.loaded_files.update(set(filtered))
for fp in fps:
fp.close()
def load_fps(self, fps):
"""Load config data by reading file objects."""
for fp in fps:
self._config.readfp(fp)
def write(self, fh):
"""Write the config to a file object."""
self._config.write(fh)
@classmethod
def _format_metadata(cls, provider, section, option, type_cls, description,
default=DefaultValue, extra=None):
"""Formats and returns the metadata for a setting.
Each setting must have:
section -- str section to which the setting belongs. This is how
settings are grouped.
option -- str id for the setting. This must be unique within the
section it appears.
type -- a ConfigType-derived type defining the type of the setting.
description -- str describing how to use the setting and where it
applies.
Each setting has the following optional parameters:
default -- The default value for the setting. If None (the default)
there is no default.
extra -- A dict of additional key/value pairs to add to the
setting metadata.
"""
if isinstance(type_cls, basestring):