本文整理汇总了Python中six.moves.configparser.RawConfigParser.write方法的典型用法代码示例。如果您正苦于以下问题:Python RawConfigParser.write方法的具体用法?Python RawConfigParser.write怎么用?Python RawConfigParser.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.configparser.RawConfigParser
的用法示例。
在下文中一共展示了RawConfigParser.write方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _test_write_pkispawn_config_file
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import write [as 别名]
def _test_write_pkispawn_config_file(self, template, expected):
"""
Test that the values we read from an ExternalCAProfile
object can be used to produce a reasonable-looking pkispawn
configuration.
"""
config = RawConfigParser()
config.optionxform = str
config.add_section("CA")
config.set("CA", "pki_req_ext_oid", template.ext_oid)
config.set("CA", "pki_req_ext_data",
hexlify(template.get_ext_data()).decode('ascii'))
out = StringIO()
config.write(out)
assert out.getvalue() == expected
示例2: convert_config_to_tribler71
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import write [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
示例3: set_config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import write [as 别名]
def set_config(self, path, value):
"""Set entry in local configuration."""
section, option = path.split('.', 1)
filename = os.path.join(self.path, '.hg', 'hgrc')
if six.PY2:
value = value.encode('utf-8')
section = section.encode('utf-8')
option = option.encode('utf-8')
config = RawConfigParser()
config.read(filename)
if not config.has_section(section):
config.add_section(section)
if (config.has_option(section, option) and
config.get(section, option) == value):
return
config.set(section, option, value)
with open(filename, 'w') as handle:
config.write(handle)
示例4: set_config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import write [as 别名]
def set_config(self, path, value):
"""
Set entry in local configuration.
"""
section, option = path.split(".", 1)
filename = os.path.join(self.path, ".hg", "hgrc")
if six.PY2:
value = value.encode("utf-8")
section = section.encode("utf-8")
option = option.encode("utf-8")
config = RawConfigParser()
config.read(filename)
if not config.has_section(section):
config.add_section(section)
if config.has_option(section, option) and config.get(section, option) == value:
return
config.set(section, option, value)
with open(filename, "w") as handle:
config.write(handle)
示例5: configure
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import write [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))
示例6: __spawn_instance
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import write [as 别名]
#.........这里部分代码省略.........
self._use_ldaps_during_spawn(config)
# Certificate subject DNs
config.set("KRA", "pki_subsystem_subject_dn",
str(DN(('cn', 'CA Subsystem'), self.subject_base)))
config.set("KRA", "pki_sslserver_subject_dn",
str(DN(('cn', self.fqdn), self.subject_base)))
config.set("KRA", "pki_audit_signing_subject_dn",
str(DN(('cn', 'KRA Audit'), self.subject_base)))
config.set(
"KRA", "pki_transport_subject_dn",
str(DN(('cn', 'KRA Transport Certificate'), self.subject_base)))
config.set(
"KRA", "pki_storage_subject_dn",
str(DN(('cn', 'KRA Storage Certificate'), self.subject_base)))
# Certificate nicknames
# Note that both the server certs and subsystem certs reuse
# the ca certs.
config.set("KRA", "pki_subsystem_nickname",
"subsystemCert cert-pki-ca")
config.set("KRA", "pki_sslserver_nickname",
"Server-Cert cert-pki-ca")
config.set("KRA", "pki_audit_signing_nickname",
"auditSigningCert cert-pki-kra")
config.set("KRA", "pki_transport_nickname",
"transportCert cert-pki-kra")
config.set("KRA", "pki_storage_nickname",
"storageCert cert-pki-kra")
# Shared db settings
# Needed because CA and KRA share the same database
# We will use the dbuser created for the CA
config.set("KRA", "pki_share_db", "True")
config.set(
"KRA", "pki_share_dbuser_dn",
str(DN(('uid', 'pkidbuser'), ('ou', 'people'), ('o', 'ipaca'))))
if not (os.path.isdir(paths.PKI_TOMCAT_ALIAS_DIR) and
os.path.isfile(paths.PKI_TOMCAT_PASSWORD_CONF)):
# generate pin which we know can be used for FIPS NSS database
pki_pin = ipautil.ipa_generate_password()
config.set("KRA", "pki_pin", pki_pin)
else:
pki_pin = None
_p12_tmpfile_handle, p12_tmpfile_name = tempfile.mkstemp(dir=paths.TMP)
if self.clone:
krafile = self.pkcs12_info[0]
shutil.copy(krafile, p12_tmpfile_name)
pent = pwd.getpwnam(self.service_user)
os.chown(p12_tmpfile_name, pent.pw_uid, pent.pw_gid)
# Security domain registration
config.set("KRA", "pki_security_domain_hostname", self.fqdn)
config.set("KRA", "pki_security_domain_https_port", "443")
config.set("KRA", "pki_security_domain_user", self.admin_user)
config.set("KRA", "pki_security_domain_password",
self.admin_password)
# Clone
config.set("KRA", "pki_clone", "True")
config.set("KRA", "pki_clone_pkcs12_path", p12_tmpfile_name)
config.set("KRA", "pki_clone_pkcs12_password", self.dm_password)
config.set("KRA", "pki_clone_setup_replication", "False")
config.set(
"KRA", "pki_clone_uri",
"https://%s" % ipautil.format_netloc(self.master_host, 443))
else:
# the admin cert file is needed for the first instance of KRA
cert = self.get_admin_cert()
# First make sure that the directory exists
parentdir = os.path.dirname(paths.ADMIN_CERT_PATH)
if not os.path.exists(parentdir):
os.makedirs(parentdir)
with open(paths.ADMIN_CERT_PATH, "wb") as admin_path:
admin_path.write(
base64.b64encode(cert.public_bytes(x509.Encoding.DER))
)
# Generate configuration file
with open(cfg_file, "w") as f:
config.write(f)
try:
DogtagInstance.spawn_instance(
self, cfg_file,
nolog_list=(self.dm_password,
self.admin_password,
pki_pin,
tmp_agent_pwd)
)
finally:
os.remove(p12_tmpfile_name)
os.remove(cfg_file)
os.remove(admin_p12_file)
shutil.move(paths.KRA_BACKUP_KEYS_P12, paths.KRACERT_P12)
logger.debug("completed creating KRA instance")
示例7: Config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import write [as 别名]
class Config(object):
"""Configuration class.
:param path: path to configuration file. If no file exists at that location,
the configuration parser will be empty.
"""
def __init__(self, path=expanduser("~/.azkabanrc")):
self.parser = RawConfigParser()
self.path = path
if exists(path):
try:
self.parser.read(self.path)
except ParsingError:
raise AzkabanError("Invalid configuration file %r.", path)
def save(self):
"""Save configuration parser back to file."""
with open(self.path, "w") as writer:
self.parser.write(writer)
def get_option(self, command, name, default=None):
"""Get option value for a command.
:param command: Command the option should be looked up for.
:param name: Name of the option.
:param default: Default value to be returned if not found in the
configuration file. If not provided, will raise
:class:`~azkaban.util.AzkabanError`.
"""
try:
return self.parser.get(command, name)
except (NoOptionError, NoSectionError):
if default is not None:
return default
else:
raise AzkabanError(
"No %(name)s found in %(path)r for %(command)s.\n"
"You can specify one by adding a `%(name)s` option in the "
"`%(command)s` section." % {"command": command, "name": name, "path": self.path}
)
def get_file_handler(self, command):
"""Add and configure file handler.
:param command: Command the options should be looked up for.
The default path can be configured via the `default.log` option in the
command's corresponding section.
"""
handler_path = osp.join(gettempdir(), "%s.log" % (command,))
try:
handler = TimedRotatingFileHandler(
self.get_option(command, "default.log", handler_path),
when="midnight", # daily backups
backupCount=1,
encoding="utf-8",
)
except IOError:
wr.warn("Unable to write to log file at %s." % (handler_path,))
else:
handler_format = "[%(levelname)s] %(asctime)s :: %(name)s :: %(message)s"
handler.setFormatter(lg.Formatter(handler_format))
return handler
示例8: Popen
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import write [as 别名]
x = Popen(['condor_submit_dag', prevdags[-1]])
x.wait()
if x.returncode != 0:
errmsg = "Error... unable to submit rescue DAG for '%s'. Automation code is aborting." % prevdags[-1]
remove_cron(cronid) # remove cron job
if email != None:
subject = sys.argv[0] + ': Error message'
send_email(FROM, email, subject, errmsg, server)
sys.exit(1)
# add number of rescue DAGs to configuration file
cp.set('configuration', 'rescue_dags', str(rescuedags))
# Write out updated configuration file
fc = open(inifile, 'w')
cp.write(fc)
fc.close()
# wait until re-running
try:
# reset to run again later
if timestep in ['hourly', 'daily']: # if hourly or daily just wait until the next run
print("Running rescue DAG")
os._exit(0) # don't use sys.exit(0) as this throws an exception that is caught by "except": https://stackoverflow.com/a/173323/1862861
else: # add a day to the crontab job and re-run then
cron = CronTab(user=True)
for job in cron.find_comment(cronid):
thisjob = job # cron job
# get a detlaT for a day
t1 = Time('2010-01-01 00:00:00')
示例9: Config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import write [as 别名]
class Config(object):
"""Configuration class.
:param path: path to configuration file. If no file exists at that location,
the configuration parser will be empty. Defaults to `~/.azkabanrc`.
"""
def __init__(self, path=None):
self.parser = RawConfigParser()
self.path = path or expanduser('~/.azkabanrc')
# TODO: make the default path be configurable via an environment variable.
if exists(self.path):
try:
self.parser.read(self.path)
except ParsingError:
raise AzkabanError('Invalid configuration file %r.', self.path)
else:
# TODO: remove this in 1.0.
if self._convert_aliases():
self.save()
self.parser.read(self.path)
def save(self):
"""Save configuration parser back to file."""
with open(self.path, 'w') as writer:
self.parser.write(writer)
def get_option(self, command, name, default=None):
"""Get option value for a command.
:param command: Command the option should be looked up for.
:param name: Name of the option.
:param default: Default value to be returned if not found in the
configuration file. If not provided, will raise
:class:`~azkaban.util.AzkabanError`.
"""
try:
return self.parser.get(command, name)
except (NoOptionError, NoSectionError):
if default is not None:
return default
else:
raise AzkabanError(
'No %(name)s found in %(path)r for %(command)s.\n'
'You can specify one by adding a `%(name)s` option in the '
'`%(command)s` section.'
% {'command': command, 'name': name, 'path': self.path}
)
def get_file_handler(self, command):
"""Add and configure file handler.
:param command: Command the options should be looked up for.
The default path can be configured via the `default.log` option in the
command's corresponding section.
"""
handler_path = osp.join(gettempdir(), '%s.log' % (command, ))
try:
handler = TimedRotatingFileHandler(
self.get_option(command, 'default.log', handler_path),
when='midnight', # daily backups
backupCount=1,
encoding='utf-8',
)
except IOError:
wr.warn('Unable to write to log file at %s.' % (handler_path, ))
else:
handler_format = '[%(levelname)s] %(asctime)s :: %(name)s :: %(message)s'
handler.setFormatter(lg.Formatter(handler_format))
return handler
def _convert_aliases(self):
"""Convert old-style aliases to new-style."""
parser = self.parser
if not parser.has_section('alias'):
return False # Nothing to do.
for alias, url in parser.items('alias'):
section = 'alias.%s' % (alias, )
if not parser.has_section(section):
# Only update if the alias doesn't yet.
parser.add_section(section)
parser.set(section, 'url', url)
parser.set(section, 'verify', 'false') # Backwards compatibility.
parser.remove_section('alias')
return True
示例10: ConfigSettings
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import write [as 别名]
#.........这里部分代码省略.........
self._config.remove_option(self._name, k)
# Prune empty sections.
if not len(self._config.options(self._name)):
self._config.remove_section(self._name)
@reraise_attribute_error
def __getattr__(self, k):
return self.__getitem__(k)
@reraise_attribute_error
def __setattr__(self, k, v):
self.__setitem__(k, v)
@reraise_attribute_error
def __delattr__(self, k):
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