本文整理匯總了Python中configparser.MissingSectionHeaderError方法的典型用法代碼示例。如果您正苦於以下問題:Python configparser.MissingSectionHeaderError方法的具體用法?Python configparser.MissingSectionHeaderError怎麽用?Python configparser.MissingSectionHeaderError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類configparser
的用法示例。
在下文中一共展示了configparser.MissingSectionHeaderError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def __init__(self):
"""Entry Point for DAX_Setup_Handler class."""
# Set the settings_file
self.settings_file = os.path.join(os.path.expanduser('~'),
'.dax_settings.ini')
# ConfigParser
self.config_parser = configparser.SafeConfigParser(allow_no_value=True)
# Set the configParser from init file or default value
if os.path.isfile(self.settings_file):
try:
self.config_parser.read(self.settings_file)
except configparser.MissingSectionHeaderError as MSHE:
self._print_error_and_exit('Missing header bracket detected. \
Please check your ini file.\n', MSHE)
else: # set to default
for section in sorted(DEFAULTS.keys()):
self.config_parser.add_section(section)
for option in list(DEFAULTS[section].keys()):
self.config_parser.set(section, option,
DEFAULTS[section][option])
示例2: load_analyzers
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def load_analyzers():
analyzers = list()
for use_case_arg in settings.args.use_cases:
for use_case_file in glob.glob(use_case_arg, recursive=True):
if not os.path.isdir(use_case_file):
logging.logger.debug("Loading use case %s" % use_case_file)
try:
analyzers.extend(AnalyzerFactory.create_multi(use_case_file))
except (ValueError, MissingSectionHeaderError, DuplicateSectionError, DuplicateOptionError) as e:
logging.logger.error("An error occured when loading %s: %s" % (use_case_file, str(e)))
return analyzers
# pylint: disable=too-many-branches
示例3: deserialize
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def deserialize(self, serialized: str) -> None:
"""Extract data from string and store it in the Configuration parser."""
updated_preferences = self.__updateSerialized(serialized)
self._parser = configparser.ConfigParser(interpolation = None)
try:
self._parser.read_string(updated_preferences)
except (configparser.MissingSectionHeaderError, configparser.DuplicateOptionError, configparser.DuplicateSectionError, configparser.ParsingError, configparser.InterpolationError) as e:
Logger.log("w", "Could not deserialize preferences file: {error}".format(error = str(e)))
self._parser = None
return
has_version = "general" in self._parser and "version" in self._parser["general"]
if has_version:
if self._parser["general"]["version"] != str(Preferences.Version):
Logger.log("w", "Could not deserialize preferences from loaded project")
self._parser = None
return
else:
return
self.__initializeSettings()
示例4: main
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def main() -> None:
options = parse_args()
global bots_config
try:
bots_config = read_config_file(options.config_file, options.bot_name)
except MissingSectionHeaderError:
sys.exit("Error: Your Botserver config file `{0}` contains an empty section header!\n"
"You need to write the names of the bots you want to run in the "
"section headers of `{0}`.".format(options.config_file))
except NoOptionError as e:
sys.exit("Error: Your Botserver config file `{0}` has a missing option `{1}` in section `{2}`!\n"
"You need to add option `{1}` with appropriate value in section `{2}` of `{0}`"
.format(options.config_file, e.option, e.section))
available_bots = list(bots_config.keys())
bots_lib_modules = load_lib_modules(available_bots)
third_party_bot_conf = parse_config_file(options.bot_config_file) if options.bot_config_file is not None else None
bot_handlers = load_bot_handlers(available_bots, bots_config, third_party_bot_conf)
message_handlers = init_message_handlers(available_bots, bots_lib_modules, bot_handlers)
app.config["BOTS_LIB_MODULES"] = bots_lib_modules
app.config["BOT_HANDLERS"] = bot_handlers
app.config["MESSAGE_HANDLERS"] = message_handlers
app.run(host=options.hostname, port=int(options.port), debug=True)
示例5: platformio_ini_config
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def platformio_ini_config(self) -> configparser.ConfigParser:
"""
Reads and parses the 'platformio.ini' PlatformIO config file into a newly created configparser.ConfigParser
instance. Note, that the file may change over time and subsequent calls may produce different results because
of this.
Raises FileNotFoundError if no 'platformio.ini' file is present. Passes out all other exceptions, most likely
caused by parsing errors (i.e. corrupted .INI format), e.g.
configparser.MissingSectionHeaderError: File contains no section headers.
It doesn't use any interpolation as we do not interested in the particular values, just presence and correctness
When using this property for comparing, make sure your other config doesn't use the interpolation either so we
just can match raw unprocessed strings.
"""
platformio_ini = configparser.ConfigParser(interpolation=None)
platformio_ini.read(self.path.joinpath('platformio.ini').resolve(strict=True))
return platformio_ini
示例6: __init__
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def __init__(self, *args, **kwargs):
"""
files: filepaths or open file objects
"""
self.files = kwargs.pop("files")
configparser.ConfigParser.__init__(self, *args, **kwargs)
for fd in self.files:
try:
self.read_file(fd)
except AttributeError:
# python 2
try:
self.readfp(fd)
except AttributeError:
self.read(fd)
except configparser.MissingSectionHeaderError:
self.read(fd)
self.auth_settings = self.get_section("auth")
self.private_cloud_settings = self.get_section("private_cloud")
示例7: from_str
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def from_str(cls: "Config", content: str) -> "Config":
config_parser = configparser.ConfigParser()
try:
config_parser.read_string(content)
except (
configparser.MissingSectionHeaderError,
configparser.ParsingError
) as e:
raise PersistError("Error parsing Config - {}: {}".format(
type(e).__name__, str(e))
)
config_dict = {}
for section in config_parser.sections():
config_dict[section] = {}
for option in config_parser.options(section):
config_dict[section][option] = config_parser.get(section, option)
return Config.from_dict(config_dict)
示例8: __init__
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def __init__(self, config_file):
if sys.version[0] == "2":
CP.__init__(self)
else:
super().__init__()
if not os.path.exists(config_file):
raise Exception("Could not find " + config_file)
f = open(config_file)
id_string = f.readline().split("=")
if id_string[0].strip().upper() in ["CAPI", "SAPI"]:
self.type = id_string[0]
else:
raise SyntaxError("Could not find API type in " + config_file)
try:
self.version = int(id_string[1].strip())
except ValueError:
raise SyntaxError("Unknown version '{}'".format(id_string[1].strip()))
except IndexError:
raise SyntaxError("Could not find API version in " + config_file)
if sys.version[0] == "2":
exceptions = (configparser.ParsingError, configparser.DuplicateSectionError)
else:
exceptions = (
configparser.ParsingError,
configparser.DuplicateSectionError,
configparser.DuplicateOptionError,
)
try:
if sys.version[0] == "2":
self.readfp(f)
else:
self.read_file(f)
except configparser.MissingSectionHeaderError:
raise SyntaxError("Missing section header")
except exceptions as e:
raise SyntaxError(e.message)
示例9: get_local_facts_from_file
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def get_local_facts_from_file(filename):
""" Retrieve local facts from fact file
Args:
filename (str): local facts file
Returns:
dict: the retrieved facts
"""
local_facts = dict()
try:
# Handle conversion of INI style facts file to json style
ini_facts = ConfigParser.SafeConfigParser()
ini_facts.read(filename)
for section in ini_facts.sections():
local_facts[section] = dict()
for key, value in ini_facts.items(section):
local_facts[section][key] = value
except (ConfigParser.MissingSectionHeaderError,
ConfigParser.ParsingError):
try:
with open(filename, 'r') as facts_file:
local_facts = json.load(facts_file)
except (ValueError, IOError):
pass
return local_facts
示例10: __read__
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def __read__(self):
"""Read the configuration file.
:except: ConfigParser.MissingSectionHeaderError if [ or ] is missing
:return: None. config_parser is read in place
"""
try:
self.config_parser.read(self.ini_settings_file)
except configparser.MissingSectionHeaderError as MSHE:
self._print_error_as_warning('Missing header bracket detected. '
'Please check your file.\n', MSHE)
示例11: test_parse_errors
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def test_parse_errors(self):
cf = self.newconfig()
self.parse_error(cf, configparser.ParsingError,
"[Foo]\n"
"{}val-without-opt-name\n".format(self.delimiters[0]))
self.parse_error(cf, configparser.ParsingError,
"[Foo]\n"
"{}val-without-opt-name\n".format(self.delimiters[1]))
e = self.parse_error(cf, configparser.MissingSectionHeaderError,
"No Section!\n")
self.assertEqual(e.args, ('<???>', 1, "No Section!\n"))
if not self.allow_no_value:
e = self.parse_error(cf, configparser.ParsingError,
"[Foo]\n wrong-indent\n")
self.assertEqual(e.args, ('<???>',))
# read_file on a real file
tricky = support.findfile("cfgparser.3")
if self.delimiters[0] == '=':
error = configparser.ParsingError
expected = (tricky,)
else:
error = configparser.MissingSectionHeaderError
expected = (tricky, 1,
' # INI with as many tricky parts as possible\n')
with open(tricky, encoding='utf-8') as f:
e = self.parse_error(cf, error, f)
self.assertEqual(e.args, expected)
示例12: test_missingsectionheadererror
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def test_missingsectionheadererror(self):
import pickle
e1 = configparser.MissingSectionHeaderError('filename', 123, 'line')
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
pickled = pickle.dumps(e1, proto)
e2 = pickle.loads(pickled)
self.assertEqual(e1.message, e2.message)
self.assertEqual(e1.args, e2.args)
self.assertEqual(e1.line, e2.line)
self.assertEqual(e1.source, e2.source)
self.assertEqual(e1.lineno, e2.lineno)
self.assertEqual(repr(e1), repr(e2))
示例13: get_config
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def get_config():
"""
Tries to find config options in the platform-specific user config file,
otherwise falls back to defaults.
"""
config_dir = get_config_dir()
config_file = os.path.join(config_dir, "newdoc.ini")
# Copy default options to start with:
options = DEFAULT_OPTIONS
# Search for matching keys in the config file; if found,
# update the options dict with them
if os.path.isfile(config_file):
config = cp.ConfigParser()
try:
config.read(config_file)
except cp.MissingSectionHeaderError:
print("Error: The [newdoc] section is required in the configuration file.")
exit(1)
for k in options.keys():
# The configparser library is different in Python 2 and 3.
# This si the only 2/3-compatible way I've found for optional keys.
try:
options[k] = config.get("newdoc", k)
except cp.NoOptionError:
pass
return options
# def convert_title_to_id(title: str, doc_type: str) -> str:
示例14: read_config
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def read_config(config_section, config_file="ants.cfg"):
"""Read indicated configuraton section and return a dict.
Uses config.optionxform to preserver upper/lower case letters
in config file.
"""
default_config = os.path.join(_ROOT, "etc", config_file)
config_path = "/etc/ants/"
system_config = os.path.join(config_path, config_file)
if not os.path.isfile(default_config):
raise OSError("Default config file not found at %s" % default_config)
config = configparser.ConfigParser(strict=False)
config.optionxform = str
try:
config.read([default_config, system_config])
except configparser.MissingSectionHeaderError as missing_section_error:
configparser.ParsingError = missing_section_error
print("Error while reading configuration from %s." % system_config)
print("Ignoring system configuraiton")
config.read([default_config])
config_dict = dict(config.items(config_section))
if use_macos_prefs:
macos_dict = macos_prefs.read_prefs(config_section)
config_dict = macos_prefs.merge_dicts(config_dict, macos_dict)
# Add base search path to config
# This is done to allow for easy append of custom paths while keeping the
# default search path as well
if config_section == "main":
config_dict["ansible_callback_plugins_base_path"] = os.path.join(
os.path.join(_ROOT, "plugins", "callback")
)
return config_dict
示例15: _parse
# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import MissingSectionHeaderError [as 別名]
def _parse(self):
if self._initialized:
return
with open(self.filename) as inifile:
try:
self.parser.read_file(inifile)
except (UnicodeDecodeError, MissingSectionHeaderError):
raise InvalidConfigurationFile()
if not self.parser.has_section(self.section):
raise MissingSettingsSection("Missing [{}] section in {}".format(self.section, self.filename))
self._initialized = True