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: check_configuration_client_password.py From DbDat with GNU General Public License v2.0 | 6 votes |
def do_check(self, configuration_file): configuration = ConfigParser.ConfigParser() try: configuration.read(configuration_file) except ConfigParser.ParsingError as e: if self.verbose: print('Ignoring parsing errors:\n' + str(e)) try: general_log_file = configuration.get('client', 'password') # if the option is found, then red! self.result['level'] = 'RED' self.result['output'] = 'Client password is in use.' except ConfigParser.NoOptionError as e: self.result['level'] = 'GREEN' self.result['output'] = 'Client password not used.' return self.result
Example #2
Source File: check_configuration_listen_addresses.py From DbDat with GNU General Public License v2.0 | 6 votes |
def do_check(self, configuration_file): configuration = ConfigParser.ConfigParser() try: configuration.read(configuration_file) except ConfigParser.ParsingError as e: if self.verbose: print('Ignoring parsing errors:\n' + str(e)) try: bind_address = configuration.get('mysqld', 'bind-address')[0] if '127.0.0.1' == bind_address or 'localhost' == bind_address: self.result['level'] = 'GREEN' self.result['output'] = 'Database listening on localhost only. (' + str(bind_address) + ')' else: self.result['level'] = 'YELLOW' self.result['output'] = 'Database listening is not localhost only (' + str(bind_address) + ')' except ConfigParser.NoOptionError as e: self.result['level'] = 'YELLOW' self.result['output'] = 'bind-address option not set, default is (\'*\')' return self.result
Example #3
Source File: check_information_bind_ip.py From DbDat with GNU General Public License v2.0 | 6 votes |
def do_check(self, configuration_file): configuration = ConfigParser.ConfigParser() try: configuration.read(configuration_file) except ConfigParser.ParsingError as e: if self.verbose: print('Ignoring parsing errors:\n' + str(e)) try: bind_address = configuration.get('httpd', 'bind_address') if '127.0.0.1' == bind_address or 'localhost' == bind_address: self.result['level'] = 'GREEN' self.result['output'] = 'Database listening on localhost only. (' + str(bind_address) + ')' else: self.result['level'] = 'YELLOW' self.result['output'] = 'Database listening is not localhost only (' + str(bind_address) + ')' except ConfigParser.NoOptionError as e: self.result['level'] = 'GREEN' self.result['output'] = 'bind-address option not set, default is 127.0.0.1 or localhost.' return self.result
Example #4
Source File: __init__.py From loom with GNU Affero General Public License v3.0 | 6 votes |
def parse_settings_file(settings_file): # dummy section name because ConfigParser needs sections PARSER_SECTION = 'settings' parser = ConfigParser.SafeConfigParser() # preserve uppercase in settings names parser.optionxform = lambda option: option.upper() try: with open(settings_file) as stream: # Add a section, since ConfigParser requires it stream = StringIO("[%s]\n" % PARSER_SECTION + stream.read()) parser.readfp(stream) except IOError: raise SystemExit( 'ERROR! Could not open file to read settings at "%s".' % settings_file) except ConfigParser.ParsingError as e: raise SystemExit( 'ERROR! Could not parse settings in file "%s".\n %s' % (settings_file, e.message)) if parser.sections() != [PARSER_SECTION]: raise SystemExit( 'ERROR! Found extra sections in settings file: "%s". ' 'Sections are not needed.' % parser.sections()) return dict(parser.items(PARSER_SECTION))
Example #5
Source File: ConfigReader.py From dcept with GNU General Public License v3.0 | 6 votes |
def load(self, path): parser = ConfigParser.SafeConfigParser() try: cfg_str = '[root]\n' + open(path, 'r').read() cfg_fp = StringIO.StringIO(cfg_str) parser = ConfigParser.RawConfigParser(allow_no_value=False) parser.readfp(cfg_fp) self.__dict__.update(parser.items("root")) except (ConfigParser.ParsingError) as e: error = str(e) line = error[error.find("[line")+5:error.find("]")].strip() raise ConfigParser.ParsingError("Failed to parse config file. Error on line: " + line) self.checkConfig()
Example #6
Source File: test_cfgparser.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_parsingerror(self): import pickle e1 = ConfigParser.ParsingError('source') e1.append(1, 'line1') e1.append(2, 'line2') e1.append(3, 'line3') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(e1.args, e2.args) self.assertEqual(e1.filename, e2.filename) self.assertEqual(e1.errors, e2.errors) self.assertEqual(repr(e1), repr(e2))
Example #7
Source File: helper.py From DbDat with GNU General Public License v2.0 | 5 votes |
def get_config_value(configuration_file, option, verbose=False): # mongodb config files do not have sections, so inject a dummy section # see: https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/ config = StringIO.StringIO() config.write('[dbdat]\n') config.write(open(configuration_file).read()) config.seek(0, os.SEEK_SET) value = None try: configuration = ConfigParser.ConfigParser() configuration.readfp(config) except ConfigParser.ParsingError as e: if verbose: print('Ignoring parsing errors:\n' + str(e)) try: value = configuration.get('dbdat', option) # clean up required value = value.split()[0] value = value.translate(None, "'") except ConfigParser.NoOptionError as e: value = None return value
Example #8
Source File: configreader.py From p2ptv-pi with MIT License | 5 votes |
def __init__(self, filename, section, defaults = None): if defaults is None: defaults = {} ConfigParser.__init__(self) self.defaults = defaults self.defaultvalues = {'string': '', 'int': 0, 'float': 0.0, 'boolean': False, 'color': None, 'bencode-list': [], 'bencode-string': '', 'bencode-fontinfo': {'name': None, 'size': None, 'style': None, 'weight': None}} self.filename = filename self.section = section dirname = os.path.dirname(self.filename) if not os.access(dirname, os.F_OK): os.makedirs(dirname) if filename.endswith('abc.conf') and not os.access(filename, os.F_OK): defaults['minport'] = str(DEFAULTPORT) try: self.read(self.filename) except MissingSectionHeaderError: oldfile = open(self.filename, 'r') oldconfig = oldfile.readlines() oldfile.close() newfile = open(self.filename, 'w') newfile.write('[' + self.section + ']\n') newfile.writelines(oldconfig) newfile.close() self.read(self.filename) except ParsingError: self.tryRepair() self.read(self.filename)
Example #9
Source File: configreader.py From p2ptv-pi with MIT License | 5 votes |
def testConfig(self, goodconfig, newline, passes = 0): if newline: testconfig = goodconfig + newline + '\r\n' newfile = StringIO(testconfig) try: testparser = ConfigParser() testparser.readfp(newfile) return testconfig except MissingSectionHeaderError: if passes > 0: return goodconfig else: return self.testConfig(goodconfig + '[' + self.section + ']\n', newline, passes=1) except ParsingError: return goodconfig
Example #10
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 #11
Source File: test_cfgparser.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_parse_errors(self): self.newconfig() self.parse_error(ConfigParser.ParsingError, "[Foo]\n extra-spaces: splat\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n extra-spaces= splat\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n:value-without-option-name\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n=value-without-option-name\n") self.parse_error(ConfigParser.MissingSectionHeaderError, "No Section!\n")
Example #12
Source File: check_configuration_error_log.py From DbDat with GNU General Public License v2.0 | 5 votes |
def do_check(self, configuration_file): configuration = ConfigParser.ConfigParser() try: configuration.read(configuration_file) except ConfigParser.ParsingError as e: if self.verbose: print('Ignoring parsing errors:\n' + str(e)) try: general_log_file = configuration.get('mysqld', 'log_error') self.result['level'] = 'GREEN' self.result['output'] = 'Error log file enabled.' log_warnings = configuration.get('mysqld', 'log_warnings') if log_warnings < 2: self.result['level'] = 'RED' self.result['output'] = 'Error log not capturing access denied events.' except ConfigParser.NoOptionError as e: self.result['level'] = 'RED' self.result['output'] = 'Error log file not enabled.' return self.result
Example #13
Source File: load_config.py From pyrocore with GNU General Public License v2.0 | 5 votes |
def load(self, optional_cfg_files=None): """ Actually load the configuation from either the default location or the given directory. """ optional_cfg_files = optional_cfg_files or [] # Guard against coding errors if self._loaded: raise RuntimeError("INTERNAL ERROR: Attempt to load configuration twice!") try: # Load configuration namespace = {} self._set_defaults(namespace, optional_cfg_files) self._load_ini(namespace, os.path.join(self.config_dir, self.CONFIG_INI)) for cfg_file in optional_cfg_files: if not os.path.isabs(cfg_file): cfg_file = os.path.join(self.config_dir, cfg_file) if os.path.exists(cfg_file): self._load_ini(namespace, cfg_file) self._validate_namespace(namespace) self._load_py(namespace, namespace["config_script"]) self._validate_namespace(namespace) for callback in namespace["config_validator_callbacks"]: callback() except ConfigParser.ParsingError as exc: raise error.UserError(exc) # Ready to go... self._loaded = True
Example #14
Source File: test_cfgparser.py From medicare-demo with Apache License 2.0 | 5 votes |
def test_parse_errors(self): self.newconfig() self.parse_error(ConfigParser.ParsingError, "[Foo]\n extra-spaces: splat\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n extra-spaces= splat\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\noption-without-value\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n:value-without-option-name\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n=value-without-option-name\n") self.parse_error(ConfigParser.MissingSectionHeaderError, "No Section!\n")
Example #15
Source File: configfile.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def _read_config(filename): """Returns a RawConfigParser that has parsed the config file specified by the passed filename.""" # check for bad config files p = RawConfigParser() fp = None try: fp = open(filename) except IOError: pass if fp is not None: try: p.readfp(fp, filename=filename) except MissingSectionHeaderError: fp.close() del fp bad_config(filename) except ParsingError: fp.close() del fp bad_config(filename) else: fp.close() return p
Example #16
Source File: metadata.py From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal | 5 votes |
def __init__(self, app): local_meta = make_splunkhome_path( ['etc', 'apps', app, 'metadata', 'local.meta']) self._cfg = ConfigParser.SafeConfigParser() # Loosen restriction on stanzas without header names. self._cfg.SECTCRE = re.compile(r'\[(?P<header>[^]]*)\]') if os.path.isfile(local_meta): # May raise ConfigParser.ParsingError self._cfg.read(local_meta) else: raise IOError('No such file: %s.' % local_meta)
Example #17
Source File: test_cfgparser.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
def test_parse_errors(self): self.newconfig() self.parse_error(ConfigParser.ParsingError, "[Foo]\n extra-spaces: splat\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n extra-spaces= splat\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n:value-without-option-name\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n=value-without-option-name\n") self.parse_error(ConfigParser.MissingSectionHeaderError, "No Section!\n")
Example #18
Source File: test_cfgparser.py From CTFCrackTools-V2 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') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(e1.args, e2.args) self.assertEqual(e1.filename, e2.filename) self.assertEqual(e1.errors, e2.errors) self.assertEqual(repr(e1), repr(e2))
Example #19
Source File: test_cfgparser.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
def test_parse_errors(self): self.newconfig() self.parse_error(ConfigParser.ParsingError, "[Foo]\n extra-spaces: splat\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n extra-spaces= splat\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n:value-without-option-name\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n=value-without-option-name\n") self.parse_error(ConfigParser.MissingSectionHeaderError, "No Section!\n")
Example #20
Source File: test_cfgparser.py From CTFCrackTools 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') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(e1.args, e2.args) self.assertEqual(e1.filename, e2.filename) self.assertEqual(e1.errors, e2.errors) self.assertEqual(repr(e1), repr(e2))
Example #21
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 #22
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 #23
Source File: test_cfgparser.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_parse_errors(self): self.newconfig() self.parse_error(ConfigParser.ParsingError, "[Foo]\n extra-spaces: splat\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n extra-spaces= splat\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n:value-without-option-name\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n=value-without-option-name\n") self.parse_error(ConfigParser.MissingSectionHeaderError, "No Section!\n")
Example #24
Source File: test_cfgparser.py From ironpython2 with Apache License 2.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.filename, e2.filename) self.assertEqual(e1.errors, e2.errors) self.assertEqual(repr(e1), repr(e2))
Example #25
Source File: __init__.py From faces with GNU General Public License v2.0 | 5 votes |
def __init__(self, defaults=None, confFile=None, *args, **kwds): """Initialize the parser. *defaults* -- defaults values. *confFile* -- the file (or list of files) to parse.""" ConfigParser.ConfigParser.__init__(self, defaults=defaults) if confFile is None: dotFileName = '.' + confFileName # Current and home directory. confFile = [os.path.join(os.getcwd(), confFileName), os.path.join(os.getcwd(), dotFileName), os.path.join(os.path.expanduser('~'), confFileName), os.path.join(os.path.expanduser('~'), dotFileName)] if os.name == 'posix': sep = getattr(os.path, 'sep', '/') # /etc/ and /etc/conf.d/ confFile.append(os.path.join(sep, 'etc', confFileName)) confFile.append(os.path.join(sep, 'etc', 'conf.d', confFileName)) else: # etc subdirectory of sys.prefix, for non-unix systems. confFile.append(os.path.join(sys.prefix, 'etc', confFileName)) for fname in confFile: try: self.read(fname) except (ConfigParser.MissingSectionHeaderError, ConfigParser.ParsingError), e: _aux_logger.warn('Troubles reading config file: %s' % e) # Stop at the first valid file. if self.has_section('imdbpy'): break
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: __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
Example #30
Source File: test_cfgparser.py From BinderFilter with MIT License | 5 votes |
def test_parse_errors(self): self.newconfig() self.parse_error(ConfigParser.ParsingError, "[Foo]\n extra-spaces: splat\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n extra-spaces= splat\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n:value-without-option-name\n") self.parse_error(ConfigParser.ParsingError, "[Foo]\n=value-without-option-name\n") self.parse_error(ConfigParser.MissingSectionHeaderError, "No Section!\n")