本文整理匯總了Python中configparser.Error方法的典型用法代碼示例。如果您正苦於以下問題:Python configparser.Error方法的具體用法?Python configparser.Error怎麽用?Python configparser.Error使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類configparser
的用法示例。
在下文中一共展示了configparser.Error方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _handle_error
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def _handle_error(self, action: str, name: str) -> typing.Iterator[None]:
"""Catch config-related exceptions and save them in self.errors."""
try:
yield
except configexc.ConfigFileErrors as e:
for err in e.errors:
new_err = err.with_text(e.basename)
self.errors.append(new_err)
except configexc.Error as e:
text = "While {} '{}'".format(action, name)
self.errors.append(configexc.ConfigErrorDesc(text, e))
except urlmatch.ParseError as e:
text = "While {} '{}' and parsing pattern".format(action, name)
self.errors.append(configexc.ConfigErrorDesc(text, e))
except keyutils.KeyParseError as e:
text = "While {} '{}' and parsing key".format(action, name)
self.errors.append(configexc.ConfigErrorDesc(text, e))
示例2: init
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def init() -> None:
"""Initialize config storage not related to the main config."""
global state
try:
state = StateConfig()
except (configparser.Error, UnicodeDecodeError) as e:
msg = "While loading state file from {}".format(standarddir.data())
desc = configexc.ConfigErrorDesc(msg, e)
raise configexc.ConfigFileErrors('state', [desc], fatal=True)
# Set the QSettings path to something like
# ~/.config/qutebrowser/qsettings/qutebrowser/qutebrowser.conf so it
# doesn't overwrite our config.
#
# This fixes one of the corruption issues here:
# https://github.com/qutebrowser/qutebrowser/issues/515
path = os.path.join(standarddir.config(auto=True), 'qsettings')
for fmt in [QSettings.NativeFormat, QSettings.IniFormat]:
QSettings.setPath(fmt, QSettings.UserScope, path)
示例3: callSolver
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def callSolver(self, isMIP):
"""Solves the problem with cplex
"""
#solve the problem
self.cplexTime = -clock()
if isMIP and self.mip:
status= CPLEX_DLL.lib.CPXmipopt(self.env, self.hprob)
if status != 0:
raise PulpSolverError("Error in CPXmipopt status="
+ str(status))
else:
status = CPLEX_DLL.lib.CPXlpopt(self.env, self.hprob)
if status != 0:
raise PulpSolverError("Error in CPXlpopt status="
+ str(status))
self.cplexTime += clock()
示例4: write_global_vcm
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def write_global_vcm(self):
print(f"Creating global config file with defaults in {GLOBAL_CONFIG_LOCATION}")
global global_config
global_config = configparser.RawConfigParser()
global_config.add_section('GlobalSettings')
global_config.set('GlobalSettings', 'openssl_binary', self.open_ssl_binary)
global_config_file = os.path.expanduser(GLOBAL_CONFIG_LOCATION)
with open(global_config_file, 'w') as configfile:
try:
global_config.write(configfile)
except configparser.Error as ex:
print(f"Error writing config file: {global_config_file} : {ex.message}")
return
示例5: write_project_vcm
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def write_project_vcm(self, project_name, local_folder, remote_folder, url_targets):
project_config = configparser.RawConfigParser()
project_config.add_section('ProjectSettings')
project_config.set('ProjectSettings', 'project_name', project_name)
project_config.set('ProjectSettings', 'local_path', os.path.join(local_folder, ''))
project_config.set('ProjectSettings', 'remote_path', os.path.join(remote_folder, ''))
project_config.set('ProjectSettings', 'url_targets', url_targets)
project_vmc_filename = os.path.join(local_folder, '.vcm')
with open(project_vmc_filename, 'w') as configfile:
try:
project_config.write(configfile)
except configparser.Error as ex:
print(f"Error writing config file: {project_vmc_filename} : {ex.message}")
return
示例6: nikto
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def nikto():
try:
project_config = VcmProjectConfig()
project_config.read_project_vcm()
except ValueError as ex:
print(ex)
return
if not click.confirm('Run nikto against the following targets: %s' % ', '.join(project_config.targets)):
return
# Nikto takes multiple hosts from a file
# BUT bear in mind advice from: https://github.com/sullo/nikto/wiki/Basic-Testing
# ie run scans separately so that memory is freed each time.
for t in project_config.targets:
output_filename = os.path.join(project_config.artifacts_folder,
f"nikto_{urlparse(t).netloc}_{time.time()}.html")
try:
# nikto -h https://www.test.com -ssl -Format html -output .
args = ["nikto", "-h", t, '-ssl', '-Format', 'html', '-output', output_filename]
print(args)
call(args)
except Exception as ex:
print(f"Error writing nikto output to: {output_filename} : {ex}")
示例7: from_file
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def from_file(cls, file):
"""Try loading given config file.
:param str file: full path to the config file to load
"""
if not os.path.exists(file):
raise ValueError("Config file not found.")
try:
config_parser = configparser.ConfigParser()
config_parser.read(file)
configuration = cls(file, config_parser)
if not configuration.check_config_sanity():
raise ValueError("Error in config file.")
else:
return configuration
except configparser.Error:
raise ValueError("Config file is invalid.")
示例8: is_valid
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def is_valid(self):
# Using BytesIO as configparser in 2.7 can't work with unicode
# see http://bugs.python.org/issue11597
with BytesIO(self.content) as buf:
self.config = configparser.ConfigParser()
try:
try:
# Try python3 method
self.config.read_string(self._content)
except AttributeError:
# Fall back to python2 method
self.config.readfp(buf) # pylint: disable=deprecated-method
except configparser.Error:
logger.warning("Invalid repo file found: '%s'", self.content)
return False
else:
return True
示例9: init_plugin_engine
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def init_plugin_engine(self):
"""Setup the plugin engine."""
self.plugin_engine = PluginEngine()
plugin_api = PluginAPI(self.req, self)
self.plugin_engine.register_api(plugin_api)
try:
enabled_plugins = self.config_plugins.get("enabled")
except configparser.Error:
enabled_plugins = []
for plugin in self.plugin_engine.get_plugins():
plugin.enabled = plugin.module_name in enabled_plugins
self.plugin_engine.activate_plugins()
示例10: open_config_file
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def open_config_file(config_file):
""" Opens config file and makes additional checks
Creates config file if it doesn't exist and makes sure it is readable and
writable by user. That prevents surprise when user is not able to save
configuration when exiting the app.
"""
dirname = os.path.dirname(config_file)
if not os.path.exists(dirname):
os.makedirs(dirname)
if not os.path.exists(config_file):
open(config_file, "w").close()
if not os.access(config_file, os.R_OK | os.W_OK):
raise Exception("File " + config_file + " is a configuration file "
"for gtg, but it cannot be read or written. "
"Please check it")
config = configparser.ConfigParser()
try:
config.read(config_file)
except configparser.Error as e:
log.warning("Problem with opening file %s: %s", config_file, e)
return config
示例11: get_repository_config
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def get_repository_config(self, repository):
"""Get config dictionary for the given repository.
If the repository section is not found in the config file,
return ``None``. If the file is invalid, raise
:exc:`configparser.Error`.
Otherwise return a dictionary with:
* ``'repository'`` -- the repository URL
* ``'username'`` -- username for authentication
* ``'password'`` -- password for authentication
:param repository:
Name or URL of the repository to find in the ``.pypirc`` file.
The repository section must be defined in the config file.
"""
servers = self._read_index_servers()
repo_config = self._find_repo_config(servers, repository)
return repo_config
示例12: _load_log_config
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def _load_log_config(log_config_append):
try:
if not hasattr(_load_log_config, "old_time"):
_load_log_config.old_time = 0
new_time = os.path.getmtime(log_config_append)
if _load_log_config.old_time != new_time:
# Reset all existing loggers before reloading config as fileConfig
# does not reset non-child loggers.
for logger in _iter_loggers():
logger.setLevel(logging.NOTSET)
logger.handlers = []
logger.propagate = 1
logging.config.fileConfig(log_config_append,
disable_existing_loggers=False)
_load_log_config.old_time = new_time
except (configparser.Error, KeyError, os.error) as exc:
raise LogConfigError(log_config_append, str(exc))
示例13: parseConfigFile
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def parseConfigFile(configFile=None):
"""Returns a configparser.SafeConfigParser instance with configs
read from the config file. Default location of the config file is
at ~/.wakatime.cfg.
"""
# get config file location from ENV
if not configFile:
configFile = getConfigFile()
configs = configparser.ConfigParser(delimiters=('='), strict=False)
try:
with open(configFile, 'r', encoding='utf-8') as fh:
try:
configs.read_file(fh)
except configparser.Error:
print(traceback.format_exc())
raise SystemExit(CONFIG_FILE_PARSE_ERROR)
except IOError:
pass
return configs
示例14: setup_logging
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def setup_logging(
default_path='etc/logging.json',
default_level=logging.INFO,
env_key='LOG_CFG'
):
"""Setup logging configuration
"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as _f:
config = json.load(_f)
try:
logging.config.dictConfig(config)
except ValueError as _e:
print("Error during reading log configuration")
print(config)
print("Does the path for filename exist?")
raise
return path
print("Falling back to default logging config")
logging.basicConfig(level=default_level)
return False
示例15: bind
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import Error [as 別名]
def bind(self, key: str,
command: typing.Optional[str],
mode: str = 'normal') -> None:
"""Bind a key to a command, with an optional key mode."""
with self._handle_error('binding', key):
seq = keyutils.KeySequence.parse(key)
if command is None:
raise configexc.Error("Can't bind {key} to None (maybe you "
"want to use config.unbind('{key}') "
"instead?)".format(key=key))
self._keyconfig.bind(seq, command, mode=mode)