Python configparser.ParsingError() Examples
The following are 30
code examples of configparser.ParsingError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
configparser
, or try the search function
.
Example #1
Source File: __init__.py From wstan with MIT License | 6 votes |
def load_ini(ini_path): """Read config from ini file.""" ini = ConfigParser() try: # utf-8 with BOM will kill ConfigParser with open(ini_path, encoding='utf-8-sig') as f: ini.read_string('[DEFAULT]\n' + f.read()) except (ParsingError, FileNotFoundError) as e: die('error reading config file: %s' % e) ini = ini['DEFAULT'] ret = {} ret.update(ini) # fix types for i in ('port', 'tun-port'): if i in ini: ret[i] = ini.getint(i) for i in ('client', 'server', 'debug', 'compatible', 'tfo'): if i in ini: ret[i] = ini.getboolean(i) for i in ret: if '-' in i: ret[i.replace('-', '_')] = ret.pop(i) return ret.items()
Example #2
Source File: test_configparser.py From ironpython3 with Apache License 2.0 | 6 votes |
def test_parsing_error(self): with self.assertRaises(ValueError) as cm: configparser.ParsingError() self.assertEqual(str(cm.exception), "Required argument `source' not " "given.") with self.assertRaises(ValueError) as cm: configparser.ParsingError(source='source', filename='filename') self.assertEqual(str(cm.exception), "Cannot specify both `filename' " "and `source'. Use `source'.") error = configparser.ParsingError(filename='source') self.assertEqual(error.source, 'source') with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always", DeprecationWarning) self.assertEqual(error.filename, 'source') error.filename = 'filename' self.assertEqual(error.source, 'filename') for warning in w: self.assertTrue(warning.category is DeprecationWarning)
Example #3
Source File: datasource_list.py From connector-plugin-sdk with MIT License | 6 votes |
def __init__(self, ini_file): self.dsnames = {} self.suite_map = {} # Read all the datasource ini files and load the test configuration. ini_files = get_all_ini_files_local_first('config') for f in ini_files: logging.debug("Reading ini file [{}]".format(f)) config = configparser.ConfigParser() # Preserve the case of elements. config.optionxform = str try: config.read(f) except configparser.ParsingError as e: logging.debug(e) continue self.add_test(load_test(config)) self.load_ini_file(ini_file)
Example #4
Source File: config.py From optimus-manager with MIT License | 6 votes |
def load_config(): logger = get_logger() base_config = configparser.ConfigParser() base_config.read(envs.DEFAULT_CONFIG_PATH) base_config = _parsed_config_to_dict(base_config) _validate_config(base_config) if not os.path.isfile(envs.USER_CONFIG_COPY_PATH): return base_config try: user_config = configparser.ConfigParser() user_config.read([envs.DEFAULT_CONFIG_PATH, envs.USER_CONFIG_COPY_PATH]) user_config = _parsed_config_to_dict(user_config) except configparser.ParsingError as e: logger.error( "Error parsing config file %s. Falling back to default config %s. Error is : %s", envs.USER_CONFIG_COPY_PATH, envs.DEFAULT_CONFIG_PATH, str(e)) return base_config corrected_config = _validate_config(user_config, fallback_config=base_config) return corrected_config
Example #5
Source File: config.py From blackmamba with MIT License | 6 votes |
def _read_config(files): config = configparser.RawConfigParser() if isinstance(files, (str, type(u''))): files = [files] found_files = [] for filename in files: try: found_files.extend(config.read(filename)) except UnicodeDecodeError: LOG.exception("There was an error decoding a config file." "The file with a problem was %s.", filename) except configparser.ParsingError: LOG.exception("There was an error trying to parse a config " "file. The file with a problem was %s.", filename) return (config, found_files)
Example #6
Source File: Preferences.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
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()
Example #7
Source File: test_configparser.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
def test_parsing_error(self): with self.assertRaises(ValueError) as cm: configparser.ParsingError() self.assertEqual(str(cm.exception), "Required argument `source' not " "given.") with self.assertRaises(ValueError) as cm: configparser.ParsingError(source='source', filename='filename') self.assertEqual(str(cm.exception), "Cannot specify both `filename' " "and `source'. Use `source'.") error = configparser.ParsingError(filename='source') self.assertEqual(error.source, 'source') with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always", DeprecationWarning) self.assertEqual(error.filename, 'source') error.filename = 'filename' self.assertEqual(error.source, 'filename') for warning in w: self.assertTrue(warning.category is DeprecationWarning)
Example #8
Source File: Config.py From topydo with GNU General Public License v3.0 | 6 votes |
def config(p_path=None, p_overrides=None): """ Retrieve the config instance. If a path is given, the instance is overwritten by the one that supplies an additional filename (for testability). Moreover, no other configuration files will be read when a path is given. Overrides will discard a setting in any configuration file and use the passed value instead. Structure: (section, option) => value The previous configuration instance will be discarded. """ if not config.instance or p_path is not None or p_overrides is not None: try: config.instance = _Config(p_path, p_overrides) except configparser.ParsingError as perr: raise ConfigError(str(perr)) from perr return config.instance
Example #9
Source File: test_configparser.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
def test_parsing_error(self): with self.assertRaises(ValueError) as cm: configparser.ParsingError() self.assertEqual(str(cm.exception), "Required argument `source' not " "given.") with self.assertRaises(ValueError) as cm: configparser.ParsingError(source='source', filename='filename') self.assertEqual(str(cm.exception), "Cannot specify both `filename' " "and `source'. Use `source'.") error = configparser.ParsingError(filename='source') self.assertEqual(error.source, 'source') with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always", DeprecationWarning) self.assertEqual(error.filename, 'source') error.filename = 'filename' self.assertEqual(error.source, 'filename') for warning in w: self.assertTrue(warning.category is DeprecationWarning)
Example #10
Source File: settings.py From catalyst with Apache License 2.0 | 6 votes |
def _read_config( *files: str, ) -> Tuple[configparser.RawConfigParser, List[str]]: config = configparser.RawConfigParser() found_files: List[str] = [] for filename in files: try: found_files.extend(config.read(filename)) except UnicodeDecodeError: logger.exception( f"There was an error decoding a config file." f" The file with a problem was {filename}." ) except configparser.ParsingError: logger.exception( f"There was an error trying to parse a config file." f" The file with a problem was {filename}." ) return config, found_files
Example #11
Source File: config.py From seedsync with Apache License 2.0 | 6 votes |
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)
Example #12
Source File: config.py From darglint with MIT License | 6 votes |
def find_config_file_in_path(path): # type: (str) -> Optional[str] """Return the config path, if it is correct, or None. Args: path: The path to check. Returns: The fully qualified path to the config file, if it is in this directory, otherwise none. """ filenames = os.listdir(path) for filename in filenames: if filename in POSSIBLE_CONFIG_FILENAMES: config = configparser.ConfigParser() fully_qualified_path = os.path.join(path, filename) try: config.read(fully_qualified_path) if 'darglint' in config.sections(): return fully_qualified_path except configparser.ParsingError: _logger.error('Unable to parse file {}'.format( fully_qualified_path )) return None
Example #13
Source File: config.py From linter-pylama with MIT License | 6 votes |
def _read_config(files): config = configparser.RawConfigParser() if isinstance(files, (str, type(u''))): files = [files] found_files = [] for filename in files: try: found_files.extend(config.read(filename)) except UnicodeDecodeError: LOG.exception("There was an error decoding a config file." "The file with a problem was %s.", filename) except configparser.ParsingError: LOG.exception("There was an error trying to parse a config " "file. The file with a problem was %s.", filename) return (config, found_files)
Example #14
Source File: test_configparser.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_parsingerror(self): import pickle e1 = configparser.ParsingError('source') e1.append(1, 'line1') e1.append(2, 'line2') e1.append(3, 'line3') 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.source, e2.source) self.assertEqual(e1.errors, e2.errors) self.assertEqual(repr(e1), repr(e2)) e1 = configparser.ParsingError(filename='filename') e1.append(1, 'line1') e1.append(2, 'line2') e1.append(3, 'line3') 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.source, e2.source) self.assertEqual(e1.errors, e2.errors) self.assertEqual(repr(e1), repr(e2))
Example #15
Source File: bangtext.py From binaryanalysis-ng with GNU Affero General Public License v3.0 | 5 votes |
def unpack_ini(fileresult, scanenvironment, offset, unpackdir): '''Verify an INI file ''' filesize = fileresult.filesize filename_full = scanenvironment.unpack_path(fileresult.filename) unpackedfilesandlabels = [] labels = [] unpackingerror = {} unpackedsize = 0 iniconfig = configparser.ConfigParser() configfile = open(filename_full, 'r') try: iniconfig.read_file(configfile) configfile.close() except: # could include: # configparser.MissingSectionHeaderError # configparser.DuplicateOptionErrorr # configparser.ParsingError configfile.close() unpackingerror = {'offset': offset+unpackedsize, 'fatal': False, 'reason': 'not a valid INI file'} return {'status': False, 'error': unpackingerror} unpackedsize = filesize labels.append('ini') return {'status': True, 'length': unpackedsize, 'labels': labels, 'filesandlabels': unpackedfilesandlabels}
Example #16
Source File: config.py From easywall with GNU General Public License v3.0 | 5 votes |
def __init__(self, config_file_path: str) -> None: if not file_exists(config_file_path): raise FileNotFoundError("config file '{}' not found".format(config_file_path)) self.config_file_path = config_file_path self.configlib = RawConfigParser() try: self.configlib.read(self.config_file_path) except ParsingError as exc: raise ParsingError( "{} is not readable by RawConfigParser. \n inner exception: {}".format( config_file_path, format_exception(exc)))
Example #17
Source File: test_configparser.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_invalid_multiline_value(self): if self.allow_no_value: self.skipTest('if no_value is allowed, ParsingError is not raised') invalid = textwrap.dedent("""\ [DEFAULT] test {0} test invalid""".format(self.delimiters[0]) ) cf = self.newconfig() with self.assertRaises(configparser.ParsingError): cf.read_string(invalid) self.assertEqual(cf.get('DEFAULT', 'test'), 'test') self.assertEqual(cf['DEFAULT']['test'], 'test')
Example #18
Source File: test_configparser.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
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)
Example #19
Source File: flake8.py From badwolf with MIT License | 5 votes |
def _read_flake8_config(self): files = [ os.path.join(self.working_dir, 'setup.cfg'), os.path.join(self.working_dir, 'tox.ini'), ] parser = configparser.RawConfigParser() try: parser.read(files) except configparser.ParsingError: logger.exception('Error parsing flake8 config file %s', files) if parser.has_section('flake8'): return dict(parser.items('flake8')) return {}
Example #20
Source File: configer.py From ants with GNU General Public License v3.0 | 5 votes |
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
Example #21
Source File: test_config.py From easywall with GNU General Public License v3.0 | 5 votes |
def test_constructor_file_not_read(self): """ TODO: Doku """ create_file_if_not_exists("test.ini") content = """[DEFAULT] goodcontent = test badcontent """ write_into_file("test.ini", content) with self.assertRaises(ParsingError): Config("test.ini")
Example #22
Source File: inenv.py From inenv with MIT License | 5 votes |
def _parse_ini(self): venv_sections = {} with open(self.ini_path) as parse_file: try: self.parser.readfp(parse_file) except ConfigParser.ParsingError: raise InenvException("Unable to parse ini file {}".format(self.ini_path)) for venv_name in self.parser.sections(): data = self._parse_section(venv_name) venv_sections[venv_name] = data return venv_sections
Example #23
Source File: fusesocconfigparser.py From fusesoc with BSD 2-Clause "Simplified" License | 5 votes |
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)
Example #24
Source File: filesystem.py From OpenDoor with GNU General Public License v3.0 | 5 votes |
def readcfg(filename): """ Read .cfg file :param str filename: input filename :raise FileSystemError :return: configparser.RawConfigParser """ expression = '^([\/a-z].*?opendoor.*?)\/' find_dir = re.search(expression, __file__, re.IGNORECASE) if None is not find_dir: os.chdir(find_dir.group()) filepath = os.path.join(os.path.sep, os.getcwd(), filename) if not os.path.isfile(filepath): raise FileSystemError("{0} is not a file ".format(filepath)) if not os.access(filepath, os.R_OK): raise FileSystemError("Configuration file {0} can not be read. Setup chmod 0644".format(filepath)) try: config = RawConfigParser() config.read(filepath) return config except (ParsingError, NoOptionError) as error: raise FileSystemError(error)
Example #25
Source File: configure.py From VectorCloud with GNU General Public License v3.0 | 5 votes |
def write_config(serial, cert_file=None, ip=None, name=None, guid=None, clear=True): home = Path.home() config_file = str(home / ".anki_vector" / "sdk_config.ini") print("Writing config file to '{}'...".format(colored(config_file, "cyan"))) config = configparser.ConfigParser(strict=False) try: config.read(config_file) except configparser.ParsingError: if os.path.exists(config_file): os.rename(config_file, config_file + "-error") if clear: config[serial] = {} if cert_file: config[serial]["cert"] = cert_file if ip: config[serial]["ip"] = ip if name: config[serial]["name"] = name if guid: config[serial]["guid"] = guid.decode("utf-8") temp_file = config_file + "-temp" if os.path.exists(config_file): os.rename(config_file, temp_file) try: with os.fdopen(os.open(config_file, os.O_WRONLY | os.O_CREAT, 0o600), 'w') as f: config.write(f) except Exception as e: if os.path.exists(temp_file): os.rename(temp_file, config_file) raise e else: if os.path.exists(temp_file): os.remove(temp_file)
Example #26
Source File: openshift_facts.py From origin-ci-tool with Apache License 2.0 | 5 votes |
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
Example #27
Source File: openshift_facts.py From origin-ci-tool with Apache License 2.0 | 5 votes |
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
Example #28
Source File: openshift_facts.py From origin-ci-tool with Apache License 2.0 | 5 votes |
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
Example #29
Source File: openshift_facts.py From origin-ci-tool with Apache License 2.0 | 5 votes |
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
Example #30
Source File: __init__.py From aws-mfa with MIT License | 5 votes |
def get_config(aws_creds_path): config = configparser.RawConfigParser() try: config.read(aws_creds_path) except configparser.ParsingError: e = sys.exc_info()[1] log_error_and_exit(logger, "There was a problem reading or parsing " "your credentials file: %s" % (e.args[0],)) return config