當前位置: 首頁>>代碼示例>>Python>>正文


Python configparser.DuplicateSectionError方法代碼示例

本文整理匯總了Python中configparser.DuplicateSectionError方法的典型用法代碼示例。如果您正苦於以下問題:Python configparser.DuplicateSectionError方法的具體用法?Python configparser.DuplicateSectionError怎麽用?Python configparser.DuplicateSectionError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在configparser的用法示例。


在下文中一共展示了configparser.DuplicateSectionError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: load_analyzers

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [as 別名]
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 
開發者ID:NVISO-BE,項目名稱:ee-outliers,代碼行數:18,代碼來源:outliers.py

示例2: deserialize

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [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

示例3: __init__

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [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

示例4: __init__

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [as 別名]
def __init__(self) -> None:
        super().__init__()
        self._filename = os.path.join(standarddir.data(), 'state')
        self.read(self._filename, encoding='utf-8')
        qt_version = qVersion()
        # We handle this here, so we can avoid setting qt_version_changed if
        # the config is brand new, but can still set it when qt_version wasn't
        # there before...
        if 'general' in self:
            old_qt_version = self['general'].get('qt_version', None)
            self.qt_version_changed = old_qt_version != qt_version
        else:
            self.qt_version_changed = False

        for sect in ['general', 'geometry', 'inspector']:
            try:
                self.add_section(sect)
            except configparser.DuplicateSectionError:
                pass

        deleted_keys = [
            ('general', 'fooled'),
            ('general', 'backend-warning-shown'),
            ('geometry', 'inspector'),
        ]
        for sect, key in deleted_keys:
            self[sect].pop(key, None)

        self['general']['qt_version'] = qt_version
        self['general']['version'] = qutebrowser.__version__ 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:32,代碼來源:configfiles.py

示例5: set_value

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [as 別名]
def set_value(self, section, option, value):
        config = configparser.ConfigParser()
        config.read(self.config_path)
        try:
            config.add_section(section)
        except configparser.DuplicateSectionError:
            pass
        config.set(section, option, value)
        self.set(config) 
開發者ID:microsoft,項目名稱:knack,代碼行數:11,代碼來源:config.py

示例6: check_no_duplicate_key

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [as 別名]
def check_no_duplicate_key(self):
        """
        Method to check if some duplicates are present in the configuration

        :return: the error (that contain message with duplicate), None if no duplicate
        """
        try:
            config = configparser.RawConfigParser(interpolation=None, strict=True)
            config.optionxform = str  # preserve case sensitivity in config keys, important for derived field names
            config.read(self.args.config)
        except (configparser.DuplicateOptionError, configparser.DuplicateSectionError) as err:
            return err
        return None 
開發者ID:NVISO-BE,項目名稱:ee-outliers,代碼行數:15,代碼來源:settings.py

示例7: test_create_multi_with_malformed_duplicate_section_strict

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [as 別名]
def test_create_multi_with_malformed_duplicate_section_strict(self):
        self.test_settings.change_configuration_path("/app/tests/unit_tests/files/analyzer_test_01.conf")

        with self.assertRaises(configparser.DuplicateSectionError):
            AnalyzerFactory.create_multi("/app/tests/unit_tests/files/use_cases/analyzer/analyzer_multi_malformed_duplicate_section.conf") 
開發者ID:NVISO-BE,項目名稱:ee-outliers,代碼行數:7,代碼來源:test_analyzer.py

示例8: test_error_on_duplicate_section_check

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [as 別名]
def test_error_on_duplicate_section_check(self):
        self.test_settings.change_configuration_path(test_whitelist_duplicate_section_file)
        result = settings.check_no_duplicate_key()
        self.assertIsInstance(result, DuplicateSectionError)

    # Test on process_configuration_files function 
開發者ID:NVISO-BE,項目名稱:ee-outliers,代碼行數:8,代碼來源:test_settings.py

示例9: ensure_required_groups

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [as 別名]
def ensure_required_groups(self, groups):
        for group in groups:
            try:
                self.debug("Adding group {0}".format(group))
                self.config.add_section(group)
            except configparser.DuplicateSectionError:
                pass 
開發者ID:wso2,項目名稱:streaming-integrator,代碼行數:9,代碼來源:inventory.py

示例10: ns_sections

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [as 別名]
def ns_sections(self, ns):
        ns = ns.strip()
        ns_sects = OrderedDict() # { id: str(section) }
        for s in self._config.sections():
            mat = _reNamespacedSection.match(s)
            if mat is None:
                continue
            if mat.group('ns') != ns:
                continue
            id_ = mat.group('id')
            if id_ in ns_sects:
                raise DuplicateSectionError("%s:%s" % (ns, id_))
            ns_sects[id_] = s
        return [ (id_, s) for id_, s in ns_sects.items() ] # [ (id, str(section)) ] 
開發者ID:zhongxinghong,項目名稱:PKUAutoElective,代碼行數:16,代碼來源:config.py

示例11: test_weird_errors

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [as 別名]
def test_weird_errors(self):
        cf = self.newconfig()
        cf.add_section("Foo")
        with self.assertRaises(configparser.DuplicateSectionError) as cm:
            cf.add_section("Foo")
        e = cm.exception
        self.assertEqual(str(e), "Section 'Foo' already exists")
        self.assertEqual(e.args, ("Foo", None, None))

        if self.strict:
            with self.assertRaises(configparser.DuplicateSectionError) as cm:
                cf.read_string(textwrap.dedent("""\
                    [Foo]
                    will this be added{equals}True
                    [Bar]
                    what about this{equals}True
                    [Foo]
                    oops{equals}this won't
                """.format(equals=self.delimiters[0])), source='<foo-bar>')
            e = cm.exception
            self.assertEqual(str(e), "While reading from '<foo-bar>' "
                                     "[line  5]: section 'Foo' already exists")
            self.assertEqual(e.args, ("Foo", '<foo-bar>', 5))

            with self.assertRaises(configparser.DuplicateOptionError) as cm:
                cf.read_dict({'Bar': {'opt': 'val', 'OPT': 'is really `opt`'}})
            e = cm.exception
            self.assertEqual(str(e), "While reading from '<dict>': option "
                                     "'opt' in section 'Bar' already exists")
            self.assertEqual(e.args, ("Bar", "opt", "<dict>", None)) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:32,代碼來源:test_configparser.py

示例12: test_duplicatesectionerror

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [as 別名]
def test_duplicatesectionerror(self):
        import pickle
        e1 = configparser.DuplicateSectionError('section', 'source', 123)
        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.section, e2.section)
            self.assertEqual(e1.source, e2.source)
            self.assertEqual(e1.lineno, e2.lineno)
            self.assertEqual(repr(e1), repr(e2)) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:14,代碼來源:test_configparser.py

示例13: update_airflow_config

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [as 別名]
def update_airflow_config(self):
        conf = self.__get_configuration()
        with open(self.airflow_cfg, 'w') as f:
            try:
                conf.add_section('cwl')
            except configparser.DuplicateSectionError:
                pass
            conf.set("cwl", "tmp_folder", os.path.join(self.airflow_home, 'tmp'))
            conf.set("core", "logging_level", "INFO")
            conf.set("core", "load_examples", "False")
            conf.set("core", "dags_are_paused_at_creation", "False")
            conf.set("webserver", "dag_default_view", "graph")
            conf.set("webserver", "dag_orientation", "TB")
            conf.set("webserver", "hide_paused_dags_by_default", "True")
            conf.write(f) 
開發者ID:Barski-lab,項目名稱:cwl-airflow,代碼行數:17,代碼來源:launch.py

示例14: __init__

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [as 別名]
def __init__(self, section, configfile):
        self._configfile = configfile
        self._section = section
        self._config = configparser.RawConfigParser()
        try:
            self._config.read(self._configfile)
            self._config.has_section(
                self._section) or self._set_default_config(self._section)
            self.__config__ = self._read_config(self._section)
        except configparser.DuplicateSectionError:
            print(u'Doppelte Sektion in der Konfigurationsdatei.')
            raise
        except:
            print(u'Ein unbekannter Fehler in der Konfigurationsdatei ist aufgetreten.')
            raise 
開發者ID:rix1337,項目名稱:RSScrawler,代碼行數:17,代碼來源:rssconfig.py

示例15: test_source_as_bytes

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import DuplicateSectionError [as 別名]
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'"
        ) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:48,代碼來源:test_configparser.py


注:本文中的configparser.DuplicateSectionError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。