本文整理汇总了Python中six.moves.configparser.SafeConfigParser.get方法的典型用法代码示例。如果您正苦于以下问题:Python SafeConfigParser.get方法的具体用法?Python SafeConfigParser.get怎么用?Python SafeConfigParser.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.configparser.SafeConfigParser
的用法示例。
在下文中一共展示了SafeConfigParser.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [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)
示例2: read_config_file
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [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'),
}
示例3: read_header
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [as 别名]
def read_header(self):
'''
Read the backup file header that contains the meta data about
this particular backup.
'''
with open(self.header) as fd:
config = SafeConfigParser()
config.readfp(fd)
self.backup_type = config.get('ipa', 'type')
self.backup_time = config.get('ipa', 'time')
self.backup_host = config.get('ipa', 'host')
self.backup_ipa_version = config.get('ipa', 'ipa_version')
self.backup_version = config.get('ipa', 'version')
self.backup_services = config.get('ipa', 'services').split(',')
示例4: ConfigHelper
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [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
示例5: setUp
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [as 别名]
def setUp(self):
super(FunctionalTestBase, self).setUp()
if not os.path.exists(TEST_CFG):
raise Exception("Unable to run the write tests without a test.ini in that defines an access_token with write privs.")
cfg = SafeConfigParser()
with open(TEST_CFG) as fp:
cfg.readfp(fp, 'test.ini')
access_token = cfg.get('write_tests', 'access_token')
try:
activity_id = cfg.get('activity_tests', 'activity_id')
except NoOptionError:
activity_id = None
self.client = Client(access_token=access_token)
self.activity_id = activity_id
示例6: load_from_config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [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)
示例7: getManifest
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [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
示例8: handle
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [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 = SafeConfigParser()
with open(config_file, 'r') as f:
config.readfp(f, config_file)
api_key = config.get("api", "key")
email = config.get("api", "email")
try:
user_profile = get_user_profile_by_email(email)
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,))
示例9: _read_config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [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'
示例10: create_database
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [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
示例11: __parse_config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [as 别名]
def __parse_config(discover_server = True):
p = SafeConfigParser()
p.read(IPA_DEFAULT_CONF)
try:
if not config.default_realm:
config.default_realm = p.get("global", "realm")
except Exception:
pass
if discover_server:
try:
s = p.get("global", "xmlrpc_uri")
server = urlsplit(s)
config.default_server.append(server.netloc)
except Exception:
pass
try:
if not config.default_domain:
config.default_domain = p.get("global", "domain")
except Exception:
pass
示例12: read
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [as 别名]
def read(config_path):
config_path = os.path.abspath(config_path)
config_root = os.path.split(config_path)[0]
parser = SafeConfigParser()
success = parser.read(config_path)
assert config_path in success, success
subns = {"pwd": os.path.abspath(os.path.curdir)}
rv = OrderedDict()
for section in parser.sections():
rv[section] = ConfigDict(config_root)
for key in parser.options(section):
rv[section][key] = parser.get(section, key, False, subns)
return rv
示例13: get
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [as 别名]
def get(self, section, option, default=None, **kwargs):
"""Wrapper around SafeConfigParser.get() with a custom default value.
This method simply wraps the base class method, but adds a `default`
keyword argument. The value of `default` is returned whenever the
config parser does not have the requested option and/or section.
"""
if not self.has_option(section, option):
return default
try:
return SafeConfigParser.get(self, section, option, **kwargs)
except ValueError as e:
# provide somewhat descriptive error
raise ValueError(
"Failed to obtain value from configuration for %s.%s. "
"Original exception was: %s" % (section, option, e))
示例14: __init__
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [as 别名]
def __init__(self, email=None, api_key=None, config_file=None,
verbose=False, retry_on_errors=True,
site=None, client=None,
cert_bundle=None, insecure=None):
if client is None:
client = _default_client()
if config_file is None:
config_file = get_default_config_filename()
if os.path.exists(config_file):
config = SafeConfigParser()
with open(config_file, 'r') as f:
config.readfp(f, config_file)
if api_key is None:
api_key = config.get("api", "key")
if email is None:
email = config.get("api", "email")
if site is None and config.has_option("api", "site"):
site = config.get("api", "site")
if cert_bundle is None and config.has_option("api", "cert_bundle"):
cert_bundle = config.get("api", "cert_bundle")
if insecure is None and config.has_option("api", "insecure"):
# Be quite strict about what is accepted so that users don't
# disable security unintentionally.
insecure_setting = config.get("api", "insecure").lower()
if insecure_setting == "true":
insecure = True
elif insecure_setting == "false":
insecure = False
else:
raise RuntimeError("insecure is set to '%s', it must be 'true' or 'false' if it is used in %s"
% (insecure_setting, config_file))
elif None in (api_key, email):
raise RuntimeError("api_key or email not specified and %s does not exist"
% (config_file,))
self.api_key = api_key
self.email = email
self.verbose = verbose
if site is not None:
if not site.startswith("http"):
site = "https://" + site
# Remove trailing "/"s from site to simplify the below logic for adding "/api"
site = site.rstrip("/")
self.base_url = site
else:
self.base_url = "https://api.zulip.com"
if self.base_url != "https://api.zulip.com" and not self.base_url.endswith("/api"):
self.base_url += "/api"
self.base_url += "/"
self.retry_on_errors = retry_on_errors
self.client_name = client
if insecure:
self.tls_verification=False
elif cert_bundle is not None:
if not os.path.isfile(cert_bundle):
raise RuntimeError("tls bundle '%s' does not exist"
%(cert_bundle,))
self.tls_verification=cert_bundle
else:
# Default behavior: verify against system CA certificates
self.tls_verification=True
示例15: GlobusConfigParser
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import get [as 别名]
class GlobusConfigParser(object):
"""
Wraps a SafeConfigParser to do modified get()s and config file loading.
"""
_GENERAL_CONF_SECTION = 'general'
def __init__(self):
self._parser = SafeConfigParser()
self._load_config()
def _load_config(self):
# TODO: /etc is not windows friendly, not sure about expanduser
try:
self._parser.read([_get_lib_config_path(), "/etc/globus.cfg",
os.path.expanduser("~/.globus.cfg")])
except MissingSectionHeaderError:
raise GlobusError(
"Failed to parse your ~/.globus.cfg Your config file may be "
"in an old format. Please visit https://tokens.globus.org/ to "
"get the latest format of this file.")
def get(self, option,
section=None, environment=None,
failover_to_general=False, check_env=False,
type_cast=str):
"""
Attempt to lookup an option in the config file. Optionally failover to
the general section if the option is not found.
Also optionally, check for a relevant environment variable, which is
named always as GLOBUS_SDK_{option.upper()}. Note that 'section'
doesn't slot into the naming at all. Otherwise, we'd have to contend
with GLOBUS_SDK_GENERAL_... for almost everything, and
GLOBUS_SDK_ENVIRONMENT\ PROD_... which is awful.
Returns None for an unfound key, rather than raising a NoOptionError.
"""
# envrionment is just a fancy name for sections that start with
# 'environment '
if environment:
section = 'environment ' + environment
# if you don't specify a section or an environment, assume it's the
# general conf section
if section is None:
section = self._GENERAL_CONF_SECTION
# if this is a config option which checks the shell env, look there
# *first* for a value -- env values have higher precedence than config
# files so that you can locally override the behavior of a command in a
# given shell or subshell
env_option_name = 'GLOBUS_SDK_{}'.format(option.upper())
value = None
if check_env and env_option_name in os.environ:
value = os.environ[env_option_name]
else:
try:
value = self._parser.get(section, option)
except (NoOptionError, NoSectionError):
if failover_to_general:
value = self.get(option,
section=self._GENERAL_CONF_SECTION)
if value is not None:
value = type_cast(value)
return value