本文整理汇总了Python中six.moves.configparser.SafeConfigParser.set方法的典型用法代码示例。如果您正苦于以下问题:Python SafeConfigParser.set方法的具体用法?Python SafeConfigParser.set怎么用?Python SafeConfigParser.set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.configparser.SafeConfigParser
的用法示例。
在下文中一共展示了SafeConfigParser.set方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import set [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 {}
示例2: from_sections
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import set [as 别名]
def from_sections(cls, sections):
config = SafeConfigParser()
for section, keyvalues in sections.items():
config.add_section(section)
for key, value in keyvalues.items():
config.set(section, key, value)
return cls(config)
示例3: _init_config_parser
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import set [as 别名]
def _init_config_parser(self, sections=None):
parser = SafeConfigParser(allow_no_value=True)
if sections:
for section in sections:
parser.add_section(section)
for key, value in sections[section].items():
parser.set(section, key,
self._value_converter.to_strings(value))
return parser
示例4: init_ini_file
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import set [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
示例5: config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import set [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
示例6: save_to_config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import set [as 别名]
def save_to_config(save_config, config_obj, verbose=False):
"""
Write all the values in the config object to a given file in the user's home folder
:param config_file: Name of config file to store in user's home folder
:param config_obj: The config object to export to config file
:param verbose: Specify if stdout should display a message
:return:
"""
parser = SafeConfigParser()
parser.read(save_config)
if not os.path.exists(save_config):
parser.add_section('settings')
for k, v in viewitems(config_obj._asdict()):
if v is not None and isinstance(v, str):
parser.set('settings', k, v)
with open(save_config, 'w') as f:
parser.write(f)
if verbose:
click.echo("Config file written to {}".format(save_config))
示例7: PackageConfigHandler
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import set [as 别名]
class PackageConfigHandler(object):
"""
Manager class for packages files for tracking installation of modules
"""
def __init__(self):
# noinspection PyUnresolvedReferences
from six.moves.configparser import SafeConfigParser
self.package_cfg = os.path.expanduser('~/Documents/site-packages/.pypi_packages')
if not os.path.isfile(self.package_cfg):
print('Creating package file')
with open(self.package_cfg, 'w') as outs:
outs.close()
self.parser = SafeConfigParser()
self.parser.read(self.package_cfg)
def save(self):
with open(self.package_cfg, 'w') as outs:
self.parser.write(outs)
def add_module(self, pkg_info):
"""
:param pkg_info: A dict that has name, url, version, summary
:return:
"""
if not self.parser.has_section(pkg_info['name']):
self.parser.add_section(pkg_info['name'])
self.parser.set(pkg_info['name'], 'url', pkg_info['url'])
self.parser.set(pkg_info['name'], 'version', pkg_info['version'])
self.parser.set(pkg_info['name'], 'summary', pkg_info['summary'])
self.parser.set(pkg_info['name'], 'files', pkg_info['files'])
self.parser.set(pkg_info['name'], 'dependency', pkg_info['dependency'])
self.save()
def list_modules(self):
return [module for module in self.parser.sections()]
def module_exists(self, name):
return self.parser.has_section(name)
def get_info(self, name):
if self.parser.has_section(name):
tbl = {}
for opt, value in self.parser.items(name):
tbl[opt] = value
return tbl
def remove_module(self, name):
self.parser.remove_section(name)
self.save()
def get_files_installed(self, section_name):
if self.parser.has_option(section_name, 'files'):
files = self.parser.get(section_name, 'files').strip()
return files.split(',')
else:
return None
def get_dependencies(self, section_name):
if self.parser.has_option(section_name, 'dependency'):
dependencies = self.parser.get(section_name, 'dependency').strip()
return set(dependencies.split(',')) if dependencies != '' else set()
else:
return None
def get_all_dependencies(self, exclude_module=()):
all_dependencies = set()
for section_name in self.parser.sections():
if section_name not in exclude_module and self.parser.has_option(section_name, 'dependency'):
dependencies = self.parser.get(section_name, 'dependency').strip()
if dependencies != '':
for dep in dependencies.split(','):
all_dependencies.add(dep)
return all_dependencies
示例8: Config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import set [as 别名]
class Config(object):
"""
Manages the configuration file
"""
def __init__(self):
"""
DEFAULT VALUES
"""
self._basescript = None
self.recentvaults = []
self.pwlength = 10
self.search_notes = False
self.search_passwd = False
self.alphabet = "abcdefghikmnopqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWXYZ_"
self.avoid_bigrams = "cl mn nm nn rn vv VV"
self._fname = self.get_config_filename()
self._parser = SafeConfigParser()
if os.path.exists(self._fname):
self._parser.read(self._fname)
if not self._parser.has_section("base"):
self._parser.add_section("base")
for num in range(10):
if (not self._parser.has_option("base", "recentvaults" + str(num))):
break
self.recentvaults.append(self._parser.get("base", "recentvaults" + str(num)))
if self._parser.has_option("base", "pwlength"):
self.pwlength = int(self._parser.get("base", "pwlength"))
if self._parser.has_option("base", "search_notes"):
if self._parser.get("base", "search_notes") == "True":
self.search_notes = True
if self._parser.has_option("base", "search_passwd"):
if self._parser.get("base", "search_passwd") == "True":
self.search_passwd = True
if self._parser.has_option("base", "alphabet"):
self.alphabet = self._parser.get("base", "alphabet")
if self._parser.has_option("base", "avoid_bigrams"):
self.avoid_bigrams = self._parser.get("base", "avoid_bigrams")
if not os.path.exists(self._fname):
self.save()
def set_basescript(self, basescript):
self._basescript = basescript
def get_basescript(self):
return self._basescript
def save(self):
if (not os.path.exists(os.path.dirname(self._fname))):
os.mkdir(os.path.dirname(self._fname))
# remove duplicates and trim to 10 items
_saved_recentvaults = []
for item in self.recentvaults:
if item in _saved_recentvaults:
continue
self._parser.set("base", "recentvaults" + str(len(_saved_recentvaults)), item)
_saved_recentvaults.append(item)
if (len(_saved_recentvaults) >= 10):
break
self._parser.set("base", "pwlength", str(self.pwlength))
self._parser.set("base", "search_notes", str(self.search_notes))
self._parser.set("base", "search_passwd", str(self.search_passwd))
self._parser.set("base", "alphabet", str(self.alphabet))
self._parser.set("base", "avoid_bigrams", str(self.avoid_bigrams))
filehandle = open(self._fname, 'w')
self._parser.write(filehandle)
filehandle.close()
@staticmethod
def get_config_filename():
"""
Returns the full filename of the config file
"""
base_fname = "loxodo"
# On Mac OS X, config files go to ~/Library/Application Support/foo/
if platform.system() == "Darwin":
base_path = os.path.join(os.path.expanduser("~"), "Library", "Application Support")
if os.path.isdir(base_path):
return os.path.join(base_path, base_fname, base_fname + ".ini")
# On Microsoft Windows, config files go to $APPDATA/foo/
if platform.system() in ("Windows", "Microsoft"):
if ("APPDATA" in os.environ):
base_path = os.environ["APPDATA"]
if os.path.isdir(base_path):
return os.path.join(base_path, base_fname, base_fname + ".ini")
# Allow config directory override as per freedesktop.org XDG Base Directory Specification
#.........这里部分代码省略.........
示例9: set
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import set [as 别名]
def set(self, name, option_name, value):
section_name = self._get_section_name(name)
return SafeConfigParser.set(self, section_name, option_name, value.replace('%', '%%'))
示例10: generate_default_engine_config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import set [as 别名]
def generate_default_engine_config(cls):
config = SafeConfigParser()
config.add_section("OPENCAFE_ENGINE")
config.set("OPENCAFE_ENGINE", "config_directory", EngineDirectoryManager.OPENCAFE_SUB_DIRS.CONFIG_DIR)
config.set("OPENCAFE_ENGINE", "data_directory", EngineDirectoryManager.OPENCAFE_SUB_DIRS.DATA_DIR)
config.set("OPENCAFE_ENGINE", "log_directory", EngineDirectoryManager.OPENCAFE_SUB_DIRS.LOG_DIR)
config.set("OPENCAFE_ENGINE", "temp_directory", EngineDirectoryManager.OPENCAFE_SUB_DIRS.TEMP_DIR)
config.set("OPENCAFE_ENGINE", "master_log_file_name", "cafe.master")
config.set("OPENCAFE_ENGINE", "logging_verbosity", "STANDARD")
config.set("OPENCAFE_ENGINE", "default_test_repo", "cloudroast")
return config
示例11: set
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import set [as 别名]
def set(self, section, option, value=None):
SafeConfigParser.set(self, section, option, value)
dispatcher.send('%s.%s' % (section, option), 'config')
示例12: generate_default_engine_config
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import set [as 别名]
def generate_default_engine_config(cls):
config = SafeConfigParser()
config.add_section('OPENCAFE_ENGINE')
config.set(
'OPENCAFE_ENGINE', 'config_directory',
EngineDirectoryManager.OPENCAFE_SUB_DIRS.CONFIG_DIR)
config.set(
'OPENCAFE_ENGINE', 'data_directory',
EngineDirectoryManager.OPENCAFE_SUB_DIRS.DATA_DIR)
config.set(
'OPENCAFE_ENGINE', 'log_directory',
EngineDirectoryManager.OPENCAFE_SUB_DIRS.LOG_DIR)
config.set(
'OPENCAFE_ENGINE', 'temp_directory',
EngineDirectoryManager.OPENCAFE_SUB_DIRS.TEMP_DIR)
config.set(
'OPENCAFE_ENGINE', 'master_log_file_name', 'cafe.master')
config.set(
'OPENCAFE_ENGINE', 'logging_verbosity', 'STANDARD')
config.set(
'OPENCAFE_ENGINE', 'default_test_repo', 'cloudroast')
return config
示例13: Csw
# 需要导入模块: from six.moves.configparser import SafeConfigParser [as 别名]
# 或者: from six.moves.configparser.SafeConfigParser import set [as 别名]
class Csw(object):
""" Base CSW server """
def __init__(self, rtconfig=None, env=None, version='3.0.0'):
""" Initialize CSW """
if not env:
self.environ = os.environ
else:
self.environ = env
self.context = config.StaticContext()
# Lazy load this when needed
# (it will permanently update global cfg namespaces)
self.sruobj = None
self.opensearchobj = None
self.oaipmhobj = None
# init kvp
self.kvp = {}
self.mode = 'csw'
self.asynchronous = False
self.soap = False
self.request = None
self.exception = False
self.status = 'OK'
self.profiles = None
self.manager = False
self.outputschemas = {}
self.mimetype = 'application/xml; charset=UTF-8'
self.encoding = 'UTF-8'
self.pretty_print = 0
self.domainquerytype = 'list'
self.orm = 'django'
self.language = {'639_code': 'en', 'text': 'english'}
self.process_time_start = time()
# define CSW implementation object (default CSW3)
self.iface = csw3.Csw3(server_csw=self)
self.request_version = version
if self.request_version == '2.0.2':
self.iface = csw2.Csw2(server_csw=self)
self.context.set_model('csw')
# load user configuration
try:
LOGGER.info('Loading user configuration')
if isinstance(rtconfig, SafeConfigParser): # serialized already
self.config = rtconfig
else:
self.config = SafeConfigParser()
if isinstance(rtconfig, dict): # dictionary
for section, options in rtconfig.items():
self.config.add_section(section)
for k, v in options.items():
self.config.set(section, k, v)
else: # configuration file
import codecs
with codecs.open(rtconfig, encoding='utf-8') as scp:
self.config.readfp(scp)
except Exception as err:
msg = 'Could not load configuration'
LOGGER.exception('%s %s: %s', msg, rtconfig, err)
self.response = self.iface.exceptionreport(
'NoApplicableCode', 'service', msg)
return
# set server.home safely
# TODO: make this more abstract
self.config.set(
'server', 'home',
os.path.dirname(os.path.join(os.path.dirname(__file__), '..'))
)
self.context.pycsw_home = self.config.get('server', 'home')
self.context.url = self.config.get('server', 'url')
log.setup_logger(self.config)
LOGGER.info('running configuration %s', rtconfig)
LOGGER.debug('QUERY_STRING: %s', self.environ['QUERY_STRING'])
# set OGC schemas location
if not self.config.has_option('server', 'ogc_schemas_base'):
self.config.set('server', 'ogc_schemas_base',
self.context.ogc_schemas_base)
# set mimetype
if self.config.has_option('server', 'mimetype'):
self.mimetype = self.config.get('server', 'mimetype').encode()
# set encoding
if self.config.has_option('server', 'encoding'):
self.encoding = self.config.get('server', 'encoding')
# set domainquerytype
if self.config.has_option('server', 'domainquerytype'):
self.domainquerytype = self.config.get('server', 'domainquerytype')
#.........这里部分代码省略.........