Python configparser.MissingSectionHeaderError() Examples

The following are 30 code examples of configparser.MissingSectionHeaderError(). 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: server.py    From python-zulip-api with Apache License 2.0 6 votes vote down vote up
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) 
Example #2
Source File: config.py    From seedsync with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: config.py    From IndicoIo-python with MIT License 6 votes vote down vote up
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") 
Example #4
Source File: dax_tools_utils.py    From dax with MIT License 6 votes vote down vote up
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]) 
Example #5
Source File: outliers.py    From ee-outliers with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #6
Source File: Preferences.py    From Uranium with GNU Lesser General Public License v3.0 6 votes vote down vote up
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: lib.py    From stm32pio with MIT License 6 votes vote down vote up
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 
Example #8
Source File: test_configparser.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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 #9
Source File: newdoc.py    From tools with GNU General Public License v3.0 5 votes vote down vote up
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: 
Example #10
Source File: configer.py    From ants with GNU General Public License v3.0 5 votes vote down vote up
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 #11
Source File: loaders.py    From prettyconf with MIT License 5 votes vote down vote up
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 
Example #12
Source File: test_runnable.py    From flambe with MIT License 5 votes vote down vote up
def test_invalid_secrets(runnable, get_secrets):
    secrets = """
        this is a text
    """

    with pytest.raises(configparser.MissingSectionHeaderError):
        runnable.inject_secrets(get_secrets(secrets)) 
Example #13
Source File: test_runnable.py    From flambe with MIT License 5 votes vote down vote up
def test_invalid_secrets2(runnable, get_secrets):
    secrets = """
        {json: tru}
    """

    with pytest.raises(configparser.MissingSectionHeaderError):
        runnable.inject_secrets(get_secrets(secrets)) 
Example #14
Source File: detect_aws_credentials.py    From pre-commit-hooks with MIT License 5 votes vote down vote up
def get_aws_secrets_from_file(credentials_file: str) -> Set[str]:
    """Extract AWS secrets from configuration files.

    Read an ini-style configuration file and return a set with all found AWS
    secret access keys.
    """
    aws_credentials_file_path = os.path.expanduser(credentials_file)
    if not os.path.exists(aws_credentials_file_path):
        return set()

    parser = configparser.ConfigParser()
    try:
        parser.read(aws_credentials_file_path)
    except configparser.MissingSectionHeaderError:
        return set()

    keys = set()
    for section in parser.sections():
        for var in (
            'aws_secret_access_key', 'aws_security_token',
            'aws_session_token',
        ):
            try:
                key = parser.get(section, var).strip()
                if key:
                    keys.add(key)
            except configparser.NoOptionError:
                pass
    return keys 
Example #15
Source File: test_configparser.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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)) 
Example #16
Source File: test_configparser.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #17
Source File: bangtext.py    From binaryanalysis-ng with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #18
Source File: parameters.py    From sumatra with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, initialiser):
        """
        Create a new parameter set from a file or string.
        """
        SafeConfigParser.__init__(self)
        try:
            if os.path.exists(initialiser):
                self.read(initialiser)
                self.source_file = initialiser
            else:
                input = StringIO(str(initialiser))  # configparser has some problems with unicode. Using str() is a crude, and probably partial fix.
                input.seek(0)
                self.readfp(input)
        except MissingSectionHeaderError:
            raise SyntaxError("Initialiser contains no section headers") 
Example #19
Source File: io_06.py    From Modern-Python-Standard-Library-Cookbook with MIT License 5 votes vote down vote up
def read_config(config_text, schema=None):
    """Read options from ``config_text`` applying given ``schema``"""
    schema = schema or {}

    cfg = configparser.ConfigParser(
        interpolation=configparser.ExtendedInterpolation()
    )
    try:
        cfg.read_string(config_text)
    except configparser.MissingSectionHeaderError:
        config_text = '[main]\n' + config_text
        cfg.read_string(config_text)

    config = {}
    for section in schema:
        options = config.setdefault(section, {})
        for option, option_schema in schema[section].items():
            options[option] = option_schema.get('default')
    for section in cfg.sections():
        options = config.setdefault(section, {})
        section_schema = schema.get(section, {})
        for option in cfg.options(section):
            option_schema = section_schema.get(option, {})
            getter = 'get' + option_schema.get('type', '')
            options[option] = getattr(cfg, getter)(section, option)
    return config 
Example #20
Source File: fusesocconfigparser.py    From fusesoc with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 #21
Source File: test_configparser.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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 #22
Source File: test_configparser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #23
Source File: test_configparser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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 #24
Source File: dax_settings.py    From dax with MIT License 5 votes vote down vote up
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) 
Example #25
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
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 #26
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
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 vote down vote up
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 vote down vote up
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: config.py    From timesketch with Apache License 2.0 4 votes vote down vote up
def load_config_file(self, config_file_path=''):
        """Load the config from file.

        Args:
            config_file_path (str): Full path to the configuration file,
                if not supplied the default path will be used, which is
                the file RC_FILENAME inside the user's home directory.

        Raises:
          IOError if the file does not exist or config does not load.
        """
        if config_file_path:
            if not os.path.isfile(config_file_path):
                error_msg = (
                    'Unable to load config file, file {0:s} does not '
                    'exist.').format(config_file_path)
                logger.error(error_msg)
                raise IOError(error_msg)
        else:
            home_path = os.path.expanduser('~')
            config_file_path = os.path.join(home_path, self.RC_FILENAME)

        if not os.path.isfile(config_file_path):
            fw = open(config_file_path, 'a')
            fw.close()

        config = configparser.ConfigParser()
        try:
            files_read = config.read([config_file_path])
        except configparser.MissingSectionHeaderError as e:
            raise IOError(
                'Unable to parse config file, with error: {0!s}'.format(e))

        if not files_read:
            logger.warning('No config read')
            return

        if 'timesketch' not in config.sections():
            logger.warning('No timesketch section in the config')
            return

        timesketch_config = config['timesketch']
        for name, value in timesketch_config.items():
            self.set_config(name, value) 
Example #30
Source File: test_configparser.py    From ironpython3 with Apache License 2.0 4 votes vote down vote up
def test_source_as_bytes(self):
        """Issue #18260."""
        lines = textwrap.dedent("""
        [badbad]
        [badbad]""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.DuplicateSectionError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "While reading from b'badbad' [line  2]: section 'badbad' "
            "already exists"
        )
        lines = textwrap.dedent("""
        [badbad]
        bad = bad
        bad = bad""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.DuplicateOptionError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "While reading from b'badbad' [line  3]: option 'bad' in section "
            "'badbad' already exists"
        )
        lines = textwrap.dedent("""
        [badbad]
        = bad""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.ParsingError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "Source contains parsing errors: b'badbad'\n\t[line  2]: '= bad'"
        )
        lines = textwrap.dedent("""
        [badbad
        bad = bad""").strip().split('\n')
        parser = configparser.ConfigParser()
        with self.assertRaises(configparser.MissingSectionHeaderError) as dse:
            parser.read_file(lines, source=b"badbad")
        self.assertEqual(
            str(dse.exception),
            "File contains no section headers.\nfile: b'badbad', line: 1\n"
            "'[badbad'"
        )