主界面和子界面共同使用同一个配置文件,会出现子界面保存,主界面也进行保存操作,可能会覆盖子界面的内容。这里的关键问题是,多个界面在操作同一个配置文件时,可能会由于文件读写的不同步导致数据丢失!
import configparser
import os
from filelock import FileLock
class MyConfigParser(configparser.ConfigParser):
"""
设置ConfigParser选项为区分大小写。
"""
def __init__(self, defaults=None):
super().__init__(defaults=defaults)
def optionxform(self, optionstr):
return optionstr
class ConfParser:
def __init__(self):
self.fileName = 'check.ini'
self.lock = FileLock(self.fileName + '.lock')
self.conf = MyConfigParser()
self.reload()
def reload(self):
"""重新加载配置文件。"""
with self.lock:
self.conf.read(self.fileName)
def readDevices(self, key):
with self.lock:
try:
return self.conf.get('devices', key)
except Exception as e:
if not self.conf.has_section('devices'):
self.conf.add_section('devices')
self.conf.set('devices', key, '')
return 'null'
def writeDevices(self, key, value):
with self.lock:
self.conf.set('devices', key, value)
self.save()
def readCheckItems(self, key):
with self.lock:
return self.conf.getboolean('checkItems', key)
def writeCheckItems(self, key, value):
with self.lock:
self.conf.set('checkItems', key, value)
self.save()
def readSection(self, key):
with self.lock:
return self.conf.items(key)
def write(self, section, key, value):
with self.lock:
self.conf.set(section, key, value)
self.save()
def read(self, section, key):
with self.lock:
return self.conf.get(section, key)
def readBoolean(self, section, key):
with self.lock:
return self.conf.getboolean(section, key)
def save(self):
"""保存配置到文件。"""
with self.lock:
with open(self.fileName, "w") as file:
self.conf.write(file)