本文整理汇总了Python中six.moves.configparser.SafeConfigParser.readfp方法的典型用法代码示例。如果您正苦于以下问题:Python SafeConfigParser.readfp方法的具体用法?Python SafeConfigParser.readfp怎么用?Python SafeConfigParser.readfp使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.configparser.SafeConfigParser
的用法示例。
在下文中一共展示了SafeConfigParser.readfp方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [as 别名]
def read(self):
"""Override base class version to avoid parsing error with the first
'RANDFILE = ...' part of the openssl file. Also, reformat _sections
to allow for the style of SSL config files where section headings can
have spaces either side of the brackets e.g.
[ sectionName ]
and comments can occur on the same line as an option e.g.
option = blah # This is option blah
Reformat _sections to """
try:
config_file = open(self._filePath)
fileTxt = config_file.read()
except Exception as e:
raise OpenSSLConfigError('Reading OpenSSL config file "%s": %s' %
(self._filePath, e))
idx = re.search('\[\s*\w*\s*\]', fileTxt).span()[0]
config_file.seek(idx)
SafeConfigParser.readfp(self, config_file)
# Filter section names and remove comments from options
for section, val in list(self._sections.items()):
newSection = section
self._sections[newSection.strip()] = \
dict([(opt, self._filtOptVal(optVal))
for opt, optVal in list(val.items())])
del self._sections[section]
self._set_required_dn_params()
示例2: Config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [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(io.StringIO(default_config))
sources.extend(extra_sources)
for fname in sources:
try:
with io.open(fname) as fp:
self.cp.readfp(fp)
except (IOError, OSError):
pass
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
示例3: getManifest
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [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
示例4: read_config_file
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [as 别名]
def read_config_file(path):
config = SafeConfigParser()
cfp = open(path, 'r')
config.readfp(cfp)
cfp.close()
return config
示例5: init_ini_file
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [as 别名]
def init_ini_file(file=args.ini_file):
cp=SafeConfigParser()
fp=open(file)
cp.optionxform = str
cp.readfp(fp)
fp.close()
cp.set('condor','lalsuite-install',lalinf_prefix)
cp.set('analysis','engine',args.engine)
cp.remove_option('analysis','nparallel')
return cp
示例6: read_header
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [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(',')
示例7: read_ini
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [as 别名]
def read_ini(cls, path, section=None):
"""read preferences from an .ini file"""
parser = ConfigParser()
parser.optionxform = str
parser.readfp(mozfile.load(path))
if section:
if section not in parser.sections():
raise PreferencesReadError("No section '%s' in %s" % (section, path))
retval = parser.items(section, raw=True)
else:
retval = parser.defaults().items()
# cast the preferences since .ini is just strings
return [(i, cls.cast(j)) for i, j in retval]
示例8: setUp
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [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
示例9: setUp
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [as 别名]
def setUp(self):
confdata = six.StringIO("""[broker]
urls = amqps://broker1.example.com:5671 amqps://broker2.example.com:5671
cert = /etc/koji-hub/plugins/client.pem
cacert = /etc/koji-hub/plugins/ca.pem
topic_prefix = koji
connect_timeout = 10
send_timeout = 60
""")
if six.PY2:
conf = SafeConfigParser()
conf.readfp(confdata)
else:
conf = ConfigParser()
conf.read_file(confdata)
self.handler = protonmsg.TimeoutHandler('amqps://broker1.example.com:5671', [], conf)
示例10: handle
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [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,))
示例11: parse_config_file
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [as 别名]
def parse_config_file(filename):
"""Parse INI files containing IMAP connection details.
Used by livetest.py and interact.py
"""
parser = SafeConfigParser(get_string_config_defaults())
with open(filename, 'r') as fh:
parser.readfp(fh)
conf = _read_config_section(parser, "DEFAULT")
if conf.expect_failure:
raise ValueError("expect_failure should not be set for the DEFAULT section")
conf.alternates = {}
for section in parser.sections():
conf.alternates[section] = _read_config_section(parser, section)
return conf
示例12: test_on_start_no_ssl
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [as 别名]
def test_on_start_no_ssl(self, SSLDomain):
confdata = six.StringIO("""[broker]
urls = amqp://broker1.example.com:5672 amqp://broker2.example.com:5672
topic_prefix = koji
connect_timeout = 10
send_timeout = 60
""")
if six.PY2:
conf = SafeConfigParser()
conf.readfp(confdata)
else:
conf = ConfigParser()
conf.read_file(confdata)
handler = protonmsg.TimeoutHandler('amqp://broker1.example.com:5672', [], conf)
event = MagicMock()
handler.on_start(event)
event.container.connect.assert_called_once_with(url='amqp://broker1.example.com:5672',
reconnect=False,
ssl_domain=None)
self.assertEqual(SSLDomain.call_count, 0)
示例13: _update_settings_from_file
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [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')))
示例14: __init__
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [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,
client_cert=None, client_cert_key=None):
# type: (Optional[str], Optional[str], Optional[str], bool, bool, Optional[str], Optional[str], Optional[str], bool, Optional[str], Optional[str]) -> None
if client is None:
client = _default_client()
# Fill values from Environment Variables if not available in Constructor
if config_file is None:
config_file = os.environ.get("ZULIP_CONFIG")
if api_key is None:
api_key = os.environ.get("ZULIP_API_KEY")
if email is None:
email = os.environ.get("ZULIP_EMAIL")
if site is None:
site = os.environ.get("ZULIP_SITE")
if client_cert is None:
client_cert = os.environ.get("ZULIP_CERT")
if client_cert_key is None:
client_cert_key = os.environ.get("ZULIP_CERT_KEY")
if cert_bundle is None:
cert_bundle = os.environ.get("ZULIP_CERT_BUNDLE")
if config_file is None:
config_file = get_default_config_filename()
if config_file is not None and 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 client_cert is None and config.has_option("api", "client_cert"):
client_cert = config.get("api", "client_cert")
if client_cert_key is None and config.has_option("api", "client_cert_key"):
client_cert_key = config.get("api", "client_cert_key")
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 site.startswith("localhost"):
site = "http://" + site
elif 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:
raise RuntimeError("Missing Zulip server URL; specify via --site or ~/.zuliprc.")
if 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 # type: Union[bool, str]
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
if client_cert is None:
if client_cert_key is not None:
raise RuntimeError("client cert key '%s' specified, but no client cert public part provided"
% (client_cert_key,))
else: # we have a client cert
if not os.path.isfile(client_cert):
raise RuntimeError("client cert '%s' does not exist"
% (client_cert,))
if client_cert_key is not None:
if not os.path.isfile(client_cert_key):
#.........这里部分代码省略.........
示例15: config_from_string
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import readfp [as 别名]
def config_from_string(value):
config = SafeConfigParser()
config.readfp(StringIO(value))
return Config(config)