免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1369 | 回复: 2
打印 上一主题 下一主题

配置文件解析 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2013-03-26 18:11 |只看该作者 |倒序浏览
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO
def tracebackExc():
    """
    Repoint the output of traceback.print_exc() from stdout
    to a string.

    @return: the output of trackback.print_exc()
    @rtype: str
    """
    exception_msg = StringIO()
    print_exc(file=exception_msg)
    exception_msg.seek(0)
    msg = exception_msg.read().strip()
    del(exception_msg)
    return msg
class ConfigParser(object):
    """
      parser config file
    """
    class Error(Exception):
        """Base class for ConfigParser exceptions."""
        pass

    class NoSectionError(Error):
        """Raised when no section matches a requested option."""
        pass

    class DuplicateSectionError(Error):
        """Raised when a section is multiply-created."""
        pass

    class NoOptionError(Error):
        """A requested option was not found."""
        pass

    def __init__(self,file_name):
        self.__section = []
        self.__section_options = {}
        self.__file_name = file_name
        self.__notes = []
        self.read(file_name)

    def read(self,file_name):
        """
        get section and option from file_name
        @param file_name : file name
        @type file_name  : str
        @return          : None
        @raise           : TypeError,OSError
        """

        if not file_name.strip() or not isinstance(file_name,basestring):
            raise TypeError,"param file_name type is empyt or is not basestring"

        if not  os.path.isfile(file_name):
            raise TypeError,"%s is not file."%file_name

        file_handler = open(file_name,"r")
        find_section = False
        self.__file_name = file_name
        local_section = ""
        local_note = ""
        file_context = file_handler.readlines()
        self.__notes = file_context
        try:
            for line in file_context:
                line = line.strip()
                if line.startswith('#') or line.startswith(';') or not line:
                    continue
                elif line.startswith('[') and line.endswith(']'):
                    local_section = line.lstrip('[')
                    local_section = local_section.rstrip(']')
                    if line in self.__section:
                        raise  self.DuplicateSectionError,"%s section already exists."%line
                    else:
                        self.__section.append(local_section)
                        self.__section_options[local_section] = []
                        find_section = True
                else:
                    if not find_section:
                        raise OSError,"Failed to find section in %s when find option"%file_name
                    self.__section_options[local_section].append(line)

        except Exception:
            file_handler.close()
            raise OSError,tracebackExc()

    def sections(self):
        """
        get all section
        """

        return self.__section

论坛徽章:
0
2 [报告]
发表于 2013-03-26 18:14 |只看该作者
    def options(self,section):
        """
        get all option by section
        """
        section = section.strip()
        options = []
        if self.__section_options.has_key(section):
            for line in  self.__section_options[section]:
                 option = line.split('=')[0].strip()
                 options.append(option)

            return options
        else:
            raise self.NoSectionError,"No section:%s"%section


    def add_section(self,section):
        """
  
        """
        section = section.strip()

        if self.__section_options.has_key(section):
            raise self.DuplicateSectionError,"Section %s already exists" % section
        else:
            self.__section.append(section)
            self.__section_options[section] = []

    def remove_section(self,section):
        """
        """
        section = section.strip()
        if self.__section_options.has_key(section):
            del self.__section_options[section]
            temp_sections = []
            for local_section in self.__section:
                if local_section == section:
                    continue
                else:
                    temp_sections.append(local_section)
            self.__section = temp_sections
        else:
            raise self.NoSectionError,"No section:%s"%section

    def has_section(self,section):
        """
        """
        section = section.strip()

        if self.__section_options.has_key(section):
            return True
        else:
            return False

    def get(self,section,option):
        """
        """
        find_option = False
        section = section.strip()
        option = option.strip()
        if self.__section_options.has_key(section):
            lines = self.__section_options[section]
            for line in lines:
                local_option = line.split('=')[0].strip()
                value = line.split('=')[-1].strip()
                if option == local_option:
                    find_option = True
                    return value
        else:
            raise self.NoSectionError,"No section:%s"%section

        if not find_option:
            raise self.NoOptionError,"Failed to find %s in %s"%(option,section)

    def has_option(self, section, option):
        """
        """
        find_option = False
        section = section.strip()
        option = option.strip()

        if self.__section_options.has_key(section):
            lines = self.__section_options[section]
            for line in lines:
                local_option = line.split('=')[0].strip()
                value = line.split('=')[-1].strip()
                if option == local_option:
                    find_option = True
        else:
            raise self.NoSectionError,"No section:%s"%section

        return find_option

    def remove_option(self,section,option):
        """
        """
        source_section = section.strip()
        section = section.strip()
        option = option.strip()
        if self.__section_options.has_key(section):
            if self.has_option(source_section,option):
                lines = self.__section_options[section]
                temp_options = []
                for line in lines:
                    local_option = line.split('=')[0].strip()
                    value = line.split('=')[-1].strip()
                    if option == local_option:
                        continue
                    else:
                        temp_options.append(line)
                self.__section_options[section] = temp_options
            else:
                raise self.NoOptionError,"Failed to find %s in %s"%(option,section)
        else:
            raise self.NoSectionError,"No section:%s"%section


论坛徽章:
0
3 [报告]
发表于 2013-03-26 18:15 |只看该作者
    def set(self, section, option, value):
        """
        """
        source_section = section.strip()

        section = section.strip()
        option_line = option + " = " + str(value)
        if self.__section_options.has_key(section):
            if self.has_option(source_section,option):
                lines = self.__section_options[section]
                temp_options = []
                for line in lines:
                    local_option = line.split('=')[0].strip()
                    value = line.split('=')[-1].strip()
                    if option == local_option:
                        temp_options.append(option_line)
                    else:
                        temp_options.append(line)
                self.__section_options[section] = temp_options
            else:
                self.__section_options[section].append(option_line)
        else:
            raise self.NoSectionError,"No section:%s"%section
              
    def get_section_notes(self,section):
        """
        """
        local_notes = []
        for line in self.__notes:
            line = line.strip()
            if not line:
                continue
            if line.startswith(';') or line.startswith('#'):
                local_notes.append(line)
            elif line.startswith('[') and line.endswith(']'):
                local_section = line.lstrip('[')
                local_section = local_section.rstrip(']')
                local_section = local_section.strip()
                if section.strip() == local_section:
                    break
                else:
                    local_notes = []
            else:
                local_notes = []
        return local_notes


    def get_option_notes(self,section,option):
        """
        """
        local_notes = []
        find_key = False
        find_section = False
        for line in self.__notes:
            line = line.strip()
            if not line:
                continue

            if line.startswith(';') or line.startswith('#'):
                local_notes.append(line)
            elif line.startswith('[') and line.endswith(']'):
                local_notes = []
                local_section = line.lstrip('[')
                local_section = local_section.rstrip(']')
                local_section = local_section.strip()
                if section.strip() == local_section:
                    find_section = True
                else:
                    find_section = False
            else:
                option_name = line.split('=')[0].strip()
                if option_name == option.strip() and find_section:
                    break
                else:
                    local_notes = []
        return local_notes

    def add(self,section,option,value):
        """
        """
        if not self.has_section(section):
            self.add_section(section)

        self.set(section,option,value)

    def write(self,file_name):
        """
        """

        f = open(file_name, "w")
        lines = []
        #print "self.__config_list", "".join(self.__config_list)
        try:
            for section in self.__section:
                local_notes = self.get_section_notes(section)

                for note in local_notes:
                    lines.append(note)
                    lines.append('\n')
                save_section = "[" + section + "]"
                lines.append(save_section)
                lines.append('\n')
                for option in self.__section_options[section]:
                    local_option = option.split('=')[0].strip()
                    local_notes = self.get_option_notes(section,local_option)
                    for note in local_notes:
                        lines.append(note)
                        lines.append('\n')

                    lines.append(option)
                    lines.append('\n')
                lines.append('\n')
            f.writelines(lines)
        finally:
            f.close()
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP