From 5ad6bdd900233202239d14aa1abe31109ba731b9 Mon Sep 17 00:00:00 2001 From: Kailigithub Date: Sat, 6 Jun 2026 03:14:31 +0800 Subject: [PATCH] fix: use context managers for file writes to prevent resource leaks Six call sites in three files wrote to disk via bare `open(...).write(...)`, which leaks file handles until garbage collection and can leave writes un-flushed if the interpreter exits before GC. Wrap each in `with` so the handle is deterministically closed after the write. [rebase: agentmain.py conflict resolved by keeping main's `if task:` skip pattern while applying PR's `with open(...)` resource management.] --- agentmain.py | 13 +++++++++---- frontends/wechatapp.py | 3 ++- ga.py | 6 ++++-- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/agentmain.py b/agentmain.py index e4a7807ff..a42d0b0ee 100644 --- a/agentmain.py +++ b/agentmain.py @@ -24,16 +24,20 @@ def load_tool_schema(suffix=''): mem_dir = os.path.join(script_dir, 'memory') if not os.path.exists(mem_dir): os.makedirs(mem_dir) mem_txt = os.path.join(mem_dir, 'global_mem.txt') -if not os.path.exists(mem_txt): open(mem_txt, 'w', encoding='utf-8').write('# [Global Memory - L2]\n') +if not os.path.exists(mem_txt): + with open(mem_txt, 'w', encoding='utf-8') as f: f.write('# [Global Memory - L2]\n') mem_insight = os.path.join(mem_dir, 'global_mem_insight.txt') if not os.path.exists(mem_insight): t = os.path.join(script_dir, f'assets/global_mem_insight_template{lang_suffix}.txt') - open(mem_insight, 'w', encoding='utf-8').write(open(t, encoding='utf-8').read() if os.path.exists(t) else '') + tpl = '' + if os.path.exists(t): + with open(t, encoding='utf-8') as src: tpl = src.read() + with open(mem_insight, 'w', encoding='utf-8') as f: f.write(tpl) cdp_cfg = os.path.join(script_dir, 'assets/tmwd_cdp_bridge/config.js') if not os.path.exists(cdp_cfg): try: os.makedirs(os.path.dirname(cdp_cfg), exist_ok=True) - open(cdp_cfg, 'w', encoding='utf-8').write(f"const TID = '__ljq_{hex(random.randint(0, 99999999))[2:8]}';") + with open(cdp_cfg, 'w', encoding='utf-8') as f: f.write(f"const TID = '__ljq_{hex(random.randint(0, 99999999))[2:8]}';") except Exception as e: print(f'[WARN] CDP config init failed: {e} — advanced web features (tmwebdriver) will be unavailable.') def get_system_prompt(): @@ -276,7 +280,8 @@ def run(self): print(f'[Reflect] drain error: {e}'); result = f'[ERROR] {e}' log_dir = os.path.join(script_dir, 'temp/reflect_logs'); os.makedirs(log_dir, exist_ok=True) script_name = os.path.splitext(os.path.basename(args.reflect))[0] - open(os.path.join(log_dir, f'{script_name}_{datetime.now():%Y-%m-%d}.log'), 'a', encoding='utf-8').write(f'[{datetime.now():%m-%d %H:%M}]\n{result}\n\n') + with open(os.path.join(log_dir, f'{script_name}_{datetime.now():%Y-%m-%d}.log'), 'a', encoding='utf-8') as f: + f.write(f'[{datetime.now():%m-%d %H:%M}]\n{result}\n\n') if (on_done := getattr(mod, 'on_done', None)): try: on_done(result) except Exception as e: print(f'[Reflect] on_done error: {e}') diff --git a/frontends/wechatapp.py b/frontends/wechatapp.py index 301f10c62..91c1a3491 100644 --- a/frontends/wechatapp.py +++ b/frontends/wechatapp.py @@ -285,7 +285,8 @@ def _dl_media(items): ct = requests.get(f'{CDN_BASE}/download?encrypted_query_param={quote(eq)}', headers={'User-Agent': UA}, timeout=60).content pt = AES.new(aes_key, AES.MODE_ECB).decrypt(ct); pt = pt[:-pt[-1]] fname = sub.get('file_name') or f'{uuid.uuid4().hex[:8]}{ext or ".bin"}' - p = os.path.join(_TEMP_DIR, fname); open(p, 'wb').write(pt) + p = os.path.join(_TEMP_DIR, fname) + with open(p, 'wb') as f: f.write(pt) paths.append(p); print(f'[WX] media saved: {fname}', file=sys.__stdout__) except Exception as e: print(f'[WX] media dl err ({key}): {e}', file=sys.__stdout__) diff --git a/ga.py b/ga.py index a9076204c..5c575bf57 100644 --- a/ga.py +++ b/ga.py @@ -394,8 +394,10 @@ def extract_robust_content(text): try: new_content = expand_file_refs(content, base_dir=self.cwd) if mode == "prepend": - old = open(path, 'r', encoding="utf-8").read() if os.path.exists(path) else "" - open(path, 'w', encoding="utf-8").write(new_content + old) + old = '' + if os.path.exists(path): + with open(path, 'r', encoding="utf-8") as f: old = f.read() + with open(path, 'w', encoding="utf-8") as f: f.write(new_content + old) else: with open(path, 'a' if mode == "append" else 'w', encoding="utf-8") as f: f.write(new_content) yield f"[Status] ✅ {mode.capitalize()} 成功 ({len(new_content)} bytes)\n"