コード例 #1
0
ファイル: IniFile.py プロジェクト: Kariyma/pythonbot
 def addGroup(self, group):
     if self.hasGroup(group):
         if debug:
             raise DuplicateGroupError(group, self.filename)
     else:
         self.content[group] = {}
         self.tainted = True
コード例 #2
0
ファイル: IniFile.py プロジェクト: Kariyma/pythonbot
    def parse(self, filename, headers=None):
        '''Parse an INI file.
        
        headers -- list of headers the parser will try to select as a default header
        '''
        # for performance reasons
        content = self.content

        if not os.path.isfile(filename):
            raise ParsingError("File not found", filename)

        try:
            # The content should be UTF-8, but legacy files can have other
            # encodings, including mixed encodings in one file. We don't attempt
            # to decode them, but we silence the errors.
            fd = io.open(filename, 'r', encoding='utf-8', errors='replace')
        except IOError as e:
            if debug:
                raise e
            else:
                return

        # parse file
        with fd:
            for line in fd:
                line = line.strip()
                # empty line
                if not line:
                    continue
                # comment
                elif line[0] == '#':
                    continue
                # new group
                elif line[0] == '[':
                    currentGroup = line.lstrip("[").rstrip("]")
                    if debug and self.hasGroup(currentGroup):
                        raise DuplicateGroupError(currentGroup, filename)
                    else:
                        content[currentGroup] = {}
                # key
                else:
                    try:
                        key, value = line.split("=", 1)
                    except ValueError:
                        raise ParsingError("Invalid line: " + line, filename)

                    key = key.strip(
                    )  # Spaces before/after '=' should be ignored
                    try:
                        if debug and self.hasKey(key, currentGroup):
                            raise DuplicateKeyError(key, currentGroup,
                                                    filename)
                        else:
                            content[currentGroup][key] = value.strip()
                    except (IndexError, UnboundLocalError):
                        raise ParsingError(
                            "Parsing error on key, group missing", filename)

        self.filename = filename
        self.tainted = False

        # check header
        if headers:
            for header in headers:
                if header in content:
                    self.defaultGroup = header
                    break
            else:
                raise ParsingError("[%s]-Header missing" % headers[0],
                                   filename)