Skip to content

Commit 0707be0

Browse files
committed
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.]
1 parent c85b59e commit 0707be0

3 files changed

Lines changed: 15 additions & 7 deletions

File tree

agentmain.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,20 @@ def load_tool_schema(suffix=''):
2424
mem_dir = os.path.join(script_dir, 'memory')
2525
if not os.path.exists(mem_dir): os.makedirs(mem_dir)
2626
mem_txt = os.path.join(mem_dir, 'global_mem.txt')
27-
if not os.path.exists(mem_txt): open(mem_txt, 'w', encoding='utf-8').write('# [Global Memory - L2]\n')
27+
if not os.path.exists(mem_txt):
28+
with open(mem_txt, 'w', encoding='utf-8') as f: f.write('# [Global Memory - L2]\n')
2829
mem_insight = os.path.join(mem_dir, 'global_mem_insight.txt')
2930
if not os.path.exists(mem_insight):
3031
t = os.path.join(script_dir, f'assets/global_mem_insight_template{lang_suffix}.txt')
31-
open(mem_insight, 'w', encoding='utf-8').write(open(t, encoding='utf-8').read() if os.path.exists(t) else '')
32+
tpl = ''
33+
if os.path.exists(t):
34+
with open(t, encoding='utf-8') as src: tpl = src.read()
35+
with open(mem_insight, 'w', encoding='utf-8') as f: f.write(tpl)
3236
cdp_cfg = os.path.join(script_dir, 'assets/tmwd_cdp_bridge/config.js')
3337
if not os.path.exists(cdp_cfg):
3438
try:
3539
os.makedirs(os.path.dirname(cdp_cfg), exist_ok=True)
36-
open(cdp_cfg, 'w', encoding='utf-8').write(f"const TID = '__ljq_{hex(random.randint(0, 99999999))[2:8]}';")
40+
with open(cdp_cfg, 'w', encoding='utf-8') as f: f.write(f"const TID = '__ljq_{hex(random.randint(0, 99999999))[2:8]}';")
3741
except Exception as e: print(f'[WARN] CDP config init failed: {e} — advanced web features (tmwebdriver) will be unavailable.')
3842

3943
def get_system_prompt():
@@ -276,7 +280,8 @@ def run(self):
276280
print(f'[Reflect] drain error: {e}'); result = f'[ERROR] {e}'
277281
log_dir = os.path.join(script_dir, 'temp/reflect_logs'); os.makedirs(log_dir, exist_ok=True)
278282
script_name = os.path.splitext(os.path.basename(args.reflect))[0]
279-
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')
283+
with open(os.path.join(log_dir, f'{script_name}_{datetime.now():%Y-%m-%d}.log'), 'a', encoding='utf-8') as f:
284+
f.write(f'[{datetime.now():%m-%d %H:%M}]\n{result}\n\n')
280285
if (on_done := getattr(mod, 'on_done', None)):
281286
try: on_done(result)
282287
except Exception as e: print(f'[Reflect] on_done error: {e}')

frontends/wechatapp.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,8 @@ def _dl_media(items):
285285
ct = requests.get(f'{CDN_BASE}/download?encrypted_query_param={quote(eq)}', headers={'User-Agent': UA}, timeout=60).content
286286
pt = AES.new(aes_key, AES.MODE_ECB).decrypt(ct); pt = pt[:-pt[-1]]
287287
fname = sub.get('file_name') or f'{uuid.uuid4().hex[:8]}{ext or ".bin"}'
288-
p = os.path.join(_TEMP_DIR, fname); open(p, 'wb').write(pt)
288+
p = os.path.join(_TEMP_DIR, fname)
289+
with open(p, 'wb') as f: f.write(pt)
289290
paths.append(p); print(f'[WX] media saved: {fname}', file=sys.__stdout__)
290291
except Exception as e:
291292
print(f'[WX] media dl err ({key}): {e}', file=sys.__stdout__)

ga.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -394,8 +394,10 @@ def extract_robust_content(text):
394394
try:
395395
new_content = expand_file_refs(content, base_dir=self.cwd)
396396
if mode == "prepend":
397-
old = open(path, 'r', encoding="utf-8").read() if os.path.exists(path) else ""
398-
open(path, 'w', encoding="utf-8").write(new_content + old)
397+
old = ''
398+
if os.path.exists(path):
399+
with open(path, 'r', encoding="utf-8") as f: old = f.read()
400+
with open(path, 'w', encoding="utf-8") as f: f.write(new_content + old)
399401
else:
400402
with open(path, 'a' if mode == "append" else 'w', encoding="utf-8") as f: f.write(new_content)
401403
yield f"[Status] ✅ {mode.capitalize()} 成功 ({len(new_content)} bytes)\n"

0 commit comments

Comments
 (0)