本文整理汇总了Python中ConfigParser.SafeConfigParser方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigParser.SafeConfigParser方法的具体用法?Python ConfigParser.SafeConfigParser怎么用?Python ConfigParser.SafeConfigParser使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConfigParser
的用法示例。
在下文中一共展示了ConfigParser.SafeConfigParser方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def __init__(self, logfile=None, verbose=True):
"""
Wrapper for the SafeConfigParser class for easy use.
@attention: config_file argument may be file path or stream.
@param logfile: file handler or file path to a log file
@type logfile: file | FileIO | StringIO | None
@param verbose: No stdout or stderr messages. Warnings and errors will be only logged to a file, if one is given
@type verbose: bool
@return: None
@rtype: None
"""
super(ConfigParserWrapper, self).__init__(
label="ConfigParserWrapper", logfile=logfile, verbose=verbose)
self._config = ConfigParser()
self._config_file_path = None
示例2: save_pyoptix_conf
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def save_pyoptix_conf(nvcc_path, compile_args, include_dirs, library_dirs, libraries):
try:
config = ConfigParser()
config.add_section('pyoptix')
config.set('pyoptix', 'nvcc_path', nvcc_path)
config.set('pyoptix', 'compile_args', os.pathsep.join(compile_args))
config.set('pyoptix', 'include_dirs', os.pathsep.join(include_dirs))
config.set('pyoptix', 'library_dirs', os.pathsep.join(library_dirs))
config.set('pyoptix', 'libraries', os.pathsep.join(libraries))
tmp = NamedTemporaryFile(mode='w+', delete=False)
config.write(tmp)
tmp.close()
config_path = os.path.join(os.path.dirname(sys.executable), 'pyoptix.conf')
check_call_sudo_if_fails(['cp', tmp.name, config_path])
check_call_sudo_if_fails(['cp', tmp.name, '/etc/pyoptix.conf'])
check_call_sudo_if_fails(['chmod', '644', config_path])
check_call_sudo_if_fails(['chmod', '644', '/etc/pyoptix.conf'])
except Exception as e:
print("PyOptiX configuration could not be saved. When you use pyoptix.Compiler, "
"nvcc path must be in PATH, OptiX library paths must be in LD_LIBRARY_PATH, and pyoptix.Compiler "
"attributes should be set manually.")
示例3: update_state
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def update_state(setting, value, append=False, write=False):
# update in-mem
if append:
current = ','.join(agent_config_vars['state'][setting])
value = '{},{}'.format(current, value) if current else value
agent_config_vars['state'][setting] = value.split(',')
else:
agent_config_vars['state'][setting] = value
logger.debug('setting {} to {}'.format(setting, value))
# update config file
if write and not cli_config_vars['testing']:
config_ini = config_ini_path()
if os.path.exists(config_ini):
config_parser = ConfigParser.SafeConfigParser()
config_parser.read(config_ini)
config_parser.set('state', setting, str(value))
with open(config_ini, 'w') as config_file:
config_parser.write(config_file)
# return new value (if append)
return value
示例4: update_state
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def update_state(setting, value, append=False):
# update in-mem
if append:
current = ','.join(agent_config_vars['state'][setting])
value = '{},{}'.format(current, value) if current else value
agent_config_vars['state'][setting] = value.split(',')
else:
agent_config_vars['state'][setting] = value
logger.debug('setting {} to {}'.format(setting, value))
# update config file
if 'TAIL' in agent_config_vars['data_format']:
config_ini = config_ini_path()
if os.path.exists(config_ini):
config_parser = ConfigParser.SafeConfigParser()
config_parser.read(config_ini)
config_parser.set('state', setting, str(value))
with open(config_ini, 'w') as config_file:
config_parser.write(config_file)
# return new value (if append)
return value
示例5: get_config_from_root
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def get_config_from_root(root):
# This might raise EnvironmentError (if setup.cfg is missing), or
# configparser.NoSectionError (if it lacks a [versioneer] section), or
# configparser.NoOptionError (if it lacks "VCS="). See the docstring at
# the top of versioneer.py for instructions on writing your setup.cfg .
setup_cfg = os.path.join(root, "setup.cfg")
parser = configparser.SafeConfigParser()
with open(setup_cfg, "r") as f:
parser.readfp(f)
VCS = parser.get("versioneer", "VCS") # mandatory
def get(parser, name):
if parser.has_option("versioneer", name):
return parser.get("versioneer", name)
return None
cfg = VersioneerConfig()
cfg.VCS = VCS
cfg.style = get(parser, "style") or ""
cfg.versionfile_source = get(parser, "versionfile_source")
cfg.versionfile_build = get(parser, "versionfile_build")
cfg.tag_prefix = get(parser, "tag_prefix")
cfg.parentdir_prefix = get(parser, "parentdir_prefix")
cfg.verbose = get(parser, "verbose")
return cfg
示例6: remove
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def remove(name, rc_file='~/.odoorpcrc'):
"""Remove the session configuration identified by `name`
from the `rc_file` file.
>>> import odoorpc
>>> odoorpc.session.remove('foo') # doctest: +SKIP
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
>>> odoorpc.session.remove(session)
:raise: `ValueError` (wrong session name)
"""
conf = ConfigParser()
conf.read([os.path.expanduser(rc_file)])
if not conf.has_section(name):
raise ValueError(
"'{}' session does not exist in {}".format(name, rc_file)
)
conf.remove_section(name)
with open(os.path.expanduser(rc_file), 'wb') as file_:
conf.write(file_)
示例7: __init__
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def __init__(self):
if sys.version_info < (3, 2):
self.parser = ConfigParser.SafeConfigParser(os.environ)
else:
self.parser = ConfigParser.ConfigParser(defaults=os.environ)
if 'RUCIO_CONFIG' in os.environ:
self.configfile = os.environ['RUCIO_CONFIG']
else:
configs = [os.path.join(confdir, 'rucio.cfg') for confdir in get_config_dirs()]
self.configfile = next(iter(filter(os.path.exists, configs)), None)
if self.configfile is None:
raise RuntimeError('Could not load Rucio configuration file. '
'Rucio looked in the following paths for a configuration file, in order:'
'\n\t' + '\n\t'.join(configs))
if not self.parser.read(self.configfile) == [self.configfile]:
raise RuntimeError('Could not load Rucio configuration file. '
'Rucio tried loading the following configuration file:'
'\n\t' + self.configfile)
示例8: getWorld
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def getWorld(scenario,session):
# Load scenario
try:
filename = getScenarioFile(scenario,session)
os.stat(filename)
first = False
except OSError:
filename = getScenarioFile(scenario)
first = True
# Get game configuration
config = SafeConfigParser()
if __DEPLOYED__:
config.read('scenarios/%s.cfg' % (scenario))
else:
config.read('/home/david/PsychSim/psychsim/examples/%s.cfg' % (scenario))
return World(filename),config,first
示例9: get_config_from_root
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def get_config_from_root(root):
"""Read the project setup.cfg file to determine Versioneer config."""
# This might raise EnvironmentError (if setup.cfg is missing), or
# configparser.NoSectionError (if it lacks a [versioneer] section), or
# configparser.NoOptionError (if it lacks "VCS="). See the docstring at
# the top of versioneer.py for instructions on writing your setup.cfg .
setup_cfg = os.path.join(root, "setup.cfg")
parser = configparser.SafeConfigParser()
with open(setup_cfg, "r") as f:
parser.readfp(f)
VCS = parser.get("versioneer", "VCS") # mandatory
def get(parser, name):
if parser.has_option("versioneer", name):
return parser.get("versioneer", name)
return None
cfg = VersioneerConfig()
cfg.VCS = VCS
cfg.style = get(parser, "style") or ""
cfg.versionfile_source = get(parser, "versionfile_source")
cfg.versionfile_build = get(parser, "versionfile_build")
cfg.tag_prefix = get(parser, "tag_prefix")
if cfg.tag_prefix in ("''", '""'):
cfg.tag_prefix = ""
cfg.parentdir_prefix = get(parser, "parentdir_prefix")
cfg.verbose = get(parser, "verbose")
return cfg
示例10: __init__
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def __init__(self, config_file, logfile=None, verbose=True):
"""
Wrapper for the SafeConfigParser class for easy use.
@attention: config_file argument may be file path or stream.
@param config_file: file handler or file path to a config file
@type config_file: file | FileIO | StringIO
@param logfile: file handler or file path to a log file
@type logfile: file | FileIO | StringIO | None
@param verbose: No stdout or stderr messages. Warnings and errors will be only logged to a file, if one is given
@type verbose: bool
@return: None
@rtype: None
"""
assert isinstance(config_file, basestring) or self.is_stream(config_file)
assert logfile is None or isinstance(logfile, basestring) or self.is_stream(logfile)
super(ConfigParserWrapper, self).__init__(logfile=logfile, verbose=verbose)
self._config = SafeConfigParser()
if isinstance(config_file, basestring) and not os.path.isfile(config_file):
self._logger.error("Config file does not exist: '{}'".format(config_file))
raise Exception("File does not exist")
if isinstance(config_file, basestring):
self._config.read(config_file)
self._config_file_path = config_file
elif self.is_stream(config_file):
self._config.readfp(config_file)
self._config_file_path = config_file.name
else:
self._logger.error("Invalid config file argument '{}'".format(config_file))
raise Exception("Unknown argument")
示例11: create
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def create():
this.config = SafeConfigParser()
return this.config
示例12: load
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def load(filename):
this.config = SafeConfigParser()
load_result = this.config.read(os.path.expanduser(filename))
if len(load_result) != 1:
raise ConfigFileNotFound("The configuration file %s does not exist" % filename)
this.filename = os.path.expanduser(filename)
示例13: get_sysdig_config
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def get_sysdig_config():
"""Read and parse Sysdig config from config.ini"""
if os.path.exists(os.path.abspath(os.path.join(__file__, os.pardir, "config.ini"))):
config_parser = ConfigParser.SafeConfigParser()
config_parser.read(os.path.abspath(os.path.join(__file__, os.pardir, "config.ini")))
try:
sysdig_api_key = config_parser.get('sysdig', 'api_key')
hostname = config_parser.get('sysdig', 'hostname')
all_metrics = config_parser.get('sysdig', 'all_metrics').split(',')
sysdig_http_proxy = config_parser.get('sysdig', 'sysdig_http_proxy')
sysdig_https_proxy = config_parser.get('sysdig', 'sysdig_https_proxy')
sysdig_metric_chunk_size= config_parser.get('sysdig', 'metric_chunk_size')
sysdig_host_chunk_size=config_parser.get('sysdig', 'host_chunk_size')
except ConfigParser.NoOptionError:
logger.error(
"Agent not correctly configured. Check config file.")
sys.exit(1)
if len(sysdig_api_key) == 0:
logger.warning(
"Agent not correctly configured(API KEY). Check config file.")
exit()
if len(hostname) == 0:
logger.warning(
"Agent not correctly configured. Check config file.")
exit()
sysdig_config = {
"sysdig_api_key": sysdig_api_key,
"hostname": hostname,
"all_metrics": all_metrics,
"httpProxy": sysdig_http_proxy,
"httpsProxy": sysdig_https_proxy,
"host_chunk_size":sysdig_host_chunk_size,
"metric_chunk_size":sysdig_metric_chunk_size
}
else:
logger.warning("No config file found. Exiting...")
exit()
return sysdig_config
示例14: get_hadoop_config
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def get_hadoop_config():
"""Read and parse Hadoop config from config.ini"""
if os.path.exists(os.path.abspath(os.path.join(__file__, os.pardir, "config.ini"))):
config_parser = ConfigParser.SafeConfigParser()
config_parser.read(os.path.abspath(os.path.join(__file__, os.pardir, "config.ini")))
try:
name_nodes = config_parser.get('hadoop', 'name_nodes')
data_nodes = config_parser.get('hadoop', 'data_nodes')
yarn_nodes = config_parser.get('hadoop', 'yarn_nodes')
except ConfigParser.NoOptionError:
logger.error(
"Agent not correctly configured. Check config file.")
sys.exit(1)
if len(name_nodes) != 0:
name_nodes = name_nodes.split(",")
else:
name_nodes = ["http://127.0.0.1:50070"]
if len(data_nodes) != 0:
data_nodes = data_nodes.split(",")
else:
data_nodes = ["http://127.0.0.1:50075"]
if len(yarn_nodes) != 0:
yarn_nodes = yarn_nodes.split(",")
else:
yarn_nodes = ["http://127.0.0.1:8088"]
hadoop_config = {
"NAME_NODES": name_nodes,
"DATA_NODES": data_nodes,
"YARN_NODES": yarn_nodes
}
else:
logger.warning("No config file found. Using defaults.")
hadoop_config = {
"NAME_NODES": ["http://127.0.0.1:50070"],
"DATA_NODES": ["http://127.0.0.1:50075"],
"YARN_NODES": ["http://127.0.0.1:8088"]
}
return hadoop_config
示例15: get_agent_config_vars
# 需要导入模块: import ConfigParser [as 别名]
# 或者: from ConfigParser import SafeConfigParser [as 别名]
def get_agent_config_vars():
if os.path.exists(os.path.abspath(os.path.join(__file__, os.pardir, "config.ini"))):
config_parser = ConfigParser.SafeConfigParser()
config_parser.read(os.path.abspath(os.path.join(__file__, os.pardir, "config.ini")))
try:
user_name = config_parser.get('insightfinder', 'user_name')
license_key = config_parser.get('insightfinder', 'license_key')
project_name = config_parser.get('insightfinder', 'project_name')
except ConfigParser.NoOptionError:
logger.error(
"Agent not correctly configured. Check config file.")
sys.exit(1)
if len(user_name) == 0:
logger.warning(
"Agent not correctly configured(user_name). Check config file.")
sys.exit(1)
if len(license_key) == 0:
logger.warning(
"Agent not correctly configured(license_key). Check config file.")
sys.exit(1)
if len(project_name) == 0:
logger.warning(
"Agent not correctly configured(project_name). Check config file.")
sys.exit(1)
config_vars = {
"userName": user_name,
"licenseKey": license_key,
"projectName": project_name
}
return config_vars
else:
logger.error(
"Agent not correctly configured. Check config file.")
sys.exit(1)