當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。