本文整理汇总了Python中six.moves.configparser.SafeConfigParser.read方法的典型用法代码示例。如果您正苦于以下问题:Python SafeConfigParser.read方法的具体用法?Python SafeConfigParser.read怎么用?Python SafeConfigParser.read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.configparser.SafeConfigParser
的用法示例。
在下文中一共展示了SafeConfigParser.read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: from_config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [as 别名]
def from_config(cls, path, **kwargs):
"""
Create a LastFM instance from a config file in the following format:
[lastfm]
api_key = myapikey
api_secret = myapisecret
username = thesquelched
password = plaintext_password
# Can be 'password' or 'hashed_password'
auth_method = password
You can also override config values with keyword arguments.
"""
config = SafeConfigParser()
config.add_section('lastfm')
config.read(os.path.expanduser(os.path.expandvars(path)))
return LastFM(
cls._getoption(config, kwargs, 'api_key'),
cls._getoption(config, kwargs, 'api_secret'),
username=cls._getoption(config, kwargs, 'username', None),
password=cls._getoption(config, kwargs, 'password', None),
auth_method=cls._getoption(config, kwargs, 'auth_method', None),
session_key=cls._getoption(config, kwargs, 'session_key', None),
url=cls._getoption(config, kwargs, 'url', None),
)
示例2: Config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [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 {}
示例3: load_from_config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [as 别名]
def load_from_config(config_file, args, values):
"""
Load config from user's home folder, and load into config object. If values are given during runtime that conflict
with values in config file, the config file values are overwritten.
:param config_file: Name of an existing config file
:param args: Array of values containing argument names from main
:param values: Array of values containing values from arguments from main
:return: key/value pairs of args/values
"""
# TODO: Handle args not existing in user config file and passed args
config = dict()
if config_file:
load_config = os.path.join(BASE_CONFIG_DIR, config_file)
if os.path.exists(load_config):
parser = SafeConfigParser()
parser.read(load_config)
for _var in CONFIG_VARS:
config[_var['var']] = parser.get('settings', _var['var'])
items = values.items()
for k, v in items:
if k in args and v is not None:
config[k] = v
for _var in CONFIG_VARS:
if _var['var'] in args and values[_var['var']] is not None:
config[_var['var']] = values[_var['var']]
if _var["var"] not in config:
click.echo(_var['error'])
return namedtuple('GenericDict', config.keys())(**config)
示例4: load
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [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
示例5: Config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [as 别名]
class Config(object):
"""A ConfigParser wrapper to support defaults when calling instance
methods, and also tied to a single section"""
SECTION = 'scrapyd'
def __init__(self, values=None, extra_sources=()):
if values is None:
sources = self._getsources()
default_config = get_data(__package__, 'default_scrapyd.conf').decode('utf8')
self.cp = SafeConfigParser()
self.cp.readfp(StringIO(default_config))
self.cp.read(sources)
for fp in extra_sources:
self.cp.readfp(fp)
else:
self.cp = SafeConfigParser(values)
self.cp.add_section(self.SECTION)
def _getsources(self):
sources = ['/etc/scrapyd/scrapyd.conf', r'c:\scrapyd\scrapyd.conf']
sources += sorted(glob.glob('/etc/scrapyd/conf.d/*'))
sources += ['scrapyd.conf']
sources += [expanduser('~/.scrapyd.conf')]
scrapy_cfg = closest_scrapy_cfg()
if scrapy_cfg:
sources.append(scrapy_cfg)
return sources
def _getany(self, method, option, default):
try:
return method(self.SECTION, option)
except (NoSectionError, NoOptionError):
if default is not None:
return default
raise
def get(self, option, default=None):
return self._getany(self.cp.get, option, default)
def getint(self, option, default=None):
return self._getany(self.cp.getint, option, default)
def getfloat(self, option, default=None):
return self._getany(self.cp.getfloat, option, default)
def getboolean(self, option, default=None):
return self._getany(self.cp.getboolean, option, default)
def items(self, section, default=None):
try:
return self.cp.items(section)
except (NoSectionError, NoOptionError):
if default is not None:
return default
raise
示例6: read_config_file
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [as 别名]
def read_config_file(config_file_path):
# type: (str) -> None
parser = SafeConfigParser()
parser.read(config_file_path)
for section in parser.sections():
bots_config[section] = {
"email": parser.get(section, 'email'),
"key": parser.get(section, 'key'),
"site": parser.get(section, 'site'),
}
示例7: logging_config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [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)
示例8: get_config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [as 别名]
def get_config(app_dir=None, platform=None):
"""
Load app configuration and return as config instance.
"""
config = ConfigParser()
path = os.environ.get("KNOWHOW_CONF")
if not path:
if not app_dir:
app_dir = get_app_dir(platform=platform)
assert app_dir
path = os.path.join(app_dir, "knowhow.ini")
if os.path.exists(path):
config.read(path)
return config
示例9: config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [as 别名]
def config(request):
path = request.config.getoption("--config")
config = SafeConfigParser()
for section, values in CONFIG_DEFAULTS.items():
config.add_section(section)
for key, value in values.items():
config.set(section, key, value)
if path:
config.read([path])
with open(path) as f:
LOG.debug("Configuration:\n%s", f.read())
return config
示例10: __init__
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [as 别名]
def __init__(self):
here = os.path.dirname(__file__)
self.filename = os.path.join(here, self._filename)
parser = SafeConfigParser()
parser.getlist = lambda s, o: parser.get(s, o).split()
parser.getlines = lambda s, o: [l.strip() for l in parser.get(s, o).splitlines() if l.strip()]
found = parser.read(self.filename)
if not found:
raise RuntimeError('failed to read app config %r' % self.filename)
getters = {}
for attr, options in self._getters.items():
getters.update(dict.fromkeys(options, getattr(parser, attr)))
def items(section):
for o in parser.options(section):
yield o, getters.get(o, parser.get)(section, o)
kwargs = [dict([('name', section)] + list(items(section)))
for section in parser.sections()]
apps = [App(**kw) for kw in kwargs]
# some consistency checks: names and ports must be unique to make it
# possible to deploy each app on each server.
names = [app.name for app in apps]
ports = [app.port for app in apps]
assert len(names) == len(set(names))
assert len(ports) == len(set(ports))
super(Config, self).__init__((app.name, app) for app in apps)
示例11: ConfigHelper
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [as 别名]
class ConfigHelper(object):
NONE_VALUE = 'None'
DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 5696
DEFAULT_CERTFILE = os.path.normpath(os.path.join(
FILE_PATH, '../demos/certs/server.crt'))
DEFAULT_KEYFILE = os.path.normpath(os.path.join(
FILE_PATH, '../demos/certs/server.key'))
DEFAULT_CA_CERTS = os.path.normpath(os.path.join(
FILE_PATH, '../demos/certs/server.crt'))
DEFAULT_SSL_VERSION = 'PROTOCOL_SSLv23'
DEFAULT_USERNAME = None
DEFAULT_PASSWORD = None
def __init__(self):
self.logger = logging.getLogger(__name__)
self.conf = SafeConfigParser()
if self.conf.read(CONFIG_FILE):
self.logger.debug("Using config file at {0}".format(CONFIG_FILE))
else:
self.logger.warning(
"Config file {0} not found".format(CONFIG_FILE))
def get_valid_value(self, direct_value, config_section,
config_option_name, default_value):
"""Returns a value that can be used as a parameter in client or
server. If a direct_value is given, that value will be returned
instead of the value from the config file. If the appropriate config
file option is not found, the default_value is returned.
:param direct_value: represents a direct value that should be used.
supercedes values from config files
:param config_section: which section of the config file to use
:param config_option_name: name of config option value
:param default_value: default value to be used if other options not
found
:returns: a value that can be used as a parameter
"""
ARG_MSG = "Using given value '{0}' for {1}"
CONF_MSG = "Using value '{0}' from configuration file {1} for {2}"
DEFAULT_MSG = "Using default value '{0}' for {1}"
if direct_value:
return_value = direct_value
self.logger.debug(ARG_MSG.format(direct_value, config_option_name))
else:
try:
return_value = self.conf.get(config_section,
config_option_name)
self.logger.debug(CONF_MSG.format(return_value,
CONFIG_FILE,
config_option_name))
except:
return_value = default_value
self.logger.debug(DEFAULT_MSG.format(default_value,
config_option_name))
if return_value == self.NONE_VALUE:
return None
else:
return return_value
示例12: Evaluator
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [as 别名]
class Evaluator(object):
APP_NAME = 'expression-evaluators'
_default_dir = 'evaluators'
def __init__(self, plugin_dir=None):
self.config = SafeConfigParser()
config_path = save_config_path(self.APP_NAME)
self.config_file = os.path.join(config_path, self.APP_NAME + ".conf")
self.config.read(self.config_file)
this_dir = os.path.abspath(os.path.dirname(__file__))
self.plugin_dir = plugin_dir or os.path.join(
this_dir, self._default_dir)
places = [self.plugin_dir, ]
[places.append(os.path.join(path, self.APP_NAME, "evaluators")) for
path in xdg_data_dirs]
PluginManagerSingleton.setBehaviour([
ConfigurablePluginManager,
VersionedPluginManager,
])
self.manager = PluginManagerSingleton.get()
self.manager.setConfigParser(self.config, self.write_config)
self.manager.setPluginInfoExtension("expr-plugin")
self.manager.setPluginPlaces(places)
self.manager.collectPlugins()
def _get_all_evaluators(self):
return self.manager.getAllPlugins()
def _get_evaluator(self, name):
pl = self.manager.getPluginByName(name)
if not pl:
raise Exception('No expression evaluator %s' % name)
return pl.plugin_object
def write_config(self):
f = open(self.config_file, "w")
self.config.write(f)
f.close()
def evaluate(self, lang, expression, *args, **kwargs):
pl = self._get_evaluator(lang)
return pl.evaluate(expression, *args, **kwargs)
示例13: start_master
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [as 别名]
def start_master(options, plugins):
cfgparser = SafeConfigParser()
cfgparser.read(options.config)
cfg = Configuration(cfgparser)
pidfile = None
user, group, umask = None, None, None
def process_init():
system.drop_privileges(user, group, umask)
time.sleep(0.1)
master = WorkerMaster(process_callback=process_init)
cfg.configure_logging()
cfg.configure_amqp()
cfg.configure_mysql()
for plugin in plugins:
for entry_point in iter_entry_points('provoke.workers', plugin):
logger.debug('Loading plugin: name=%s', entry_point.name)
register = entry_point.load()
register(master, cfgparser)
break
else:
raise BadPlugin(plugin)
for res, limits in cfg.get_rlimits():
resource.setrlimit(res, limits)
if options.daemon:
logger.debug('Daemonizing master process')
pidfile = cfg.get_pidfile()
stdout, stderr, stdin = cfg.get_stdio_redirects()
user, group, umask = cfg.get_worker_privileges()
if stdout or stderr or stdin:
system.redirect_stdio(stdout, stderr, stdin)
system.daemonize()
with system.PidFile(pidfile):
handle_signals()
try:
master.run()
finally:
master.wait()
示例14: _read_config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [as 别名]
def _read_config(self, config_name):
parser = SafeConfigParser()
parser.read(config_name)
try:
self.ssl = parser.get("vars", "ssl").lower() in ["1", "true"]
except (NoSectionError, NoOptionError):
self.ssl = True
if self.ssl:
try:
self.trust_store_path = parser.get("vars", "trust_store_path")
except (NoSectionError, NoOptionError):
self.trust_store_path = '/etc/pki/vdsm'
else:
self.trust_store_path = None
try:
self.management_port = parser.get("addresses", "management_port")
except (NoSectionError, NoOptionError):
self.management_port = '54321'
示例15: create_database
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import read [as 别名]
def create_database(config_file):
parser = SafeConfigParser()
parser.read(config_file)
# Determine which database connection to use.
database_connection = parser.get('app:main', 'install_database_connection')
if database_connection is None:
database_connection = parser.get('app:main', 'database_connection')
if database_connection is None:
database_connection = 'sqlite:///%s' % parser.get('app:main', 'database_file')
if database_connection is None:
print('Unable to determine correct database connection.')
exit(1)
'''Initialize the database file.'''
# Initialize the database connection.
engine = create_engine(database_connection)
MetaData(bind=engine)
install_session = scoped_session(sessionmaker(bind=engine, autoflush=False, autocommit=True))
model = mapping.init(database_connection)
return install_session, model