| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- import configparser
- import os
- from threading import Lock
- class ConfigIni:
- def __init__(self, filename):
- self.filename = filename
- if not os.path.exists(self.filename):
- # 如果不存在,创建文件并写入初始内容
- with open(self.filename, 'w', encoding='utf-8') as config_file:
- config_file.write("# 示例配置文件\n")
- self.config = configparser.ConfigParser()
- self.lock = Lock()
- self.load()
- def load(self):
- with open(self.filename, 'r', encoding='utf-8') as configfile:
- self.config.read_file(configfile)
- def save(self):
- with open(self.filename, 'w', encoding='utf-8') as configfile:
- self.config.write(configfile)
- def get(self, section, key, default=""):
- with self.lock:
- try:
- if not self.config.has_option(section, key):
- return default
- return self.config.get(section, key)
- except (configparser.NoSectionError, configparser.NoOptionError):
- return default
- def get_int(self, section, key, default="0"):
- return int(self.get(section, key, default))
- def set(self, section, key, value):
- with self.lock:
- if not self.config.has_section(section):
- self.config.add_section(section)
- self.config.set(section, key, value)
- self.save()
- def set_int(self, section, key, value):
- self.set(section, key, str(value))
- def get_section_keys(self, section):
- with self.lock:
- if self.config.has_section(section):
- return dict(self.config.items(section))
- else:
- return {}
|