当前位置: 首页>>代码示例>>Python>>正文


Python configparser.ParsingError方法代码示例

本文整理汇总了Python中configparser.ParsingError方法的典型用法代码示例。如果您正苦于以下问题:Python configparser.ParsingError方法的具体用法?Python configparser.ParsingError怎么用?Python configparser.ParsingError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在configparser的用法示例。


在下文中一共展示了configparser.ParsingError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _read_config

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [as 别名]
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) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:20,代码来源:config.py

示例2: find_config_file_in_path

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [as 别名]
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 
开发者ID:terrencepreilly,项目名称:darglint,代码行数:27,代码来源:config.py

示例3: config

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [as 别名]
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 
开发者ID:bram85,项目名称:topydo,代码行数:21,代码来源:Config.py

示例4: load_ini

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [as 别名]
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() 
开发者ID:krrr,项目名称:wstan,代码行数:27,代码来源:__init__.py

示例5: test_parsing_error

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [as 别名]
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) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:20,代码来源:test_configparser.py

示例6: deserialize

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [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() 
开发者ID:Ultimaker,项目名称:Uranium,代码行数:24,代码来源:Preferences.py

示例7: load_config

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [as 别名]
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 
开发者ID:Askannz,项目名称:optimus-manager,代码行数:27,代码来源:config.py

示例8: __init__

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [as 别名]
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) 
开发者ID:tableau,项目名称:connector-plugin-sdk,代码行数:22,代码来源:datasource_list.py

示例9: _read_config

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [as 别名]
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 
开发者ID:catalyst-team,项目名称:catalyst,代码行数:23,代码来源:settings.py

示例10: from_str

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [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) 
开发者ID:ipsingh06,项目名称:seedsync,代码行数:19,代码来源:config.py

示例11: __init__

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [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) 
开发者ID:olofk,项目名称:fusesoc,代码行数:40,代码来源:fusesocconfigparser.py

示例12: write_config

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [as 别名]
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) 
开发者ID:rmountjoy92,项目名称:VectorCloud,代码行数:37,代码来源:configure.py

示例13: get_local_facts_from_file

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [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 
开发者ID:openshift,项目名称:origin-ci-tool,代码行数:29,代码来源:openshift_facts.py

示例14: get_config

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [as 别名]
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 
开发者ID:broamski,项目名称:aws-mfa,代码行数:11,代码来源:__init__.py

示例15: readcfg

# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ParsingError [as 别名]
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) 
开发者ID:stanislav-web,项目名称:OpenDoor,代码行数:29,代码来源:filesystem.py


注:本文中的configparser.ParsingError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。