Răsfoiți Sursa

fix(quiz): 修复多进程同时写入日志bug

- 移除 cached_property 依赖并替换为直接文件操作
- 集成 filelock 库以确保多线程安全的日志写入
- 将日志文件创建逻辑封装到专用方法中
- 修改文件写入逻辑以支持并发访问控制
- 移除不再需要的文件关闭方法
- 添加文件操作同步机制确保数据完整性
AzurTian 8 luni în urmă
părinte
comite
8113a32d90
1 a modificat fișierele cu 12 adăugiri și 9 ștergeri
  1. 12 9
      tasks/Quiz/debug.py

+ 12 - 9
tasks/Quiz/debug.py

@@ -3,35 +3,38 @@
 # github https://github.com/runhey
 # github https://github.com/runhey
 import re
 import re
 
 
-from cached_property import cached_property
 from pathlib import Path
 from pathlib import Path
 
 
-from module.logger import logger
+from filelock import FileLock
 
 
 
 
 def remove_symbols(text):
 def remove_symbols(text):
     return re.sub(r'[^\w\s]', '', text)
     return re.sub(r'[^\w\s]', '', text)
 
 
+
 class Debugger:
 class Debugger:
 
 
-    @cached_property
-    def fn(self):
-        # 以添加方式打开一个文件
+    def _log_file(self) -> Path:
         file: Path = Path(f'./log/quiz/supplement.txt')
         file: Path = Path(f'./log/quiz/supplement.txt')
         if not file.parent.exists():
         if not file.parent.exists():
             file.parent.mkdir(parents=True)
             file.parent.mkdir(parents=True)
         if not file.exists():
         if not file.exists():
             file.touch()
             file.touch()
-        f = open(str(file), 'a', encoding='utf-8')
-        return f
+        return file
 
 
     def append_one(self, question: str, options: list[str]):
     def append_one(self, question: str, options: list[str]):
         question = remove_symbols(question)
         question = remove_symbols(question)
         options = [remove_symbols(option) for option in options]
         options = [remove_symbols(option) for option in options]
-        self.fn.write(f'{question},{options[0]},{options[1]},{options[2]},{options[3]}\n')
+        file = self._log_file()
+        lock = FileLock(f"{file}.lock")
+        line = f'{question},{options[0]},{options[1]},{options[2]},{options[3]}\n'
+        with lock:
+            with open(file, 'a', encoding='utf-8') as f:
+                f.write(line)
+                f.flush()
 
 
     def close_fn(self):
     def close_fn(self):
-        self.fn.close()
+        return
 
 
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':