From 86c35ead8642624e5b115e373452e8716a1dfea4 Mon Sep 17 00:00:00 2001 From: Kailigithub Date: Sat, 23 May 2026 03:16:57 +0000 Subject: [PATCH] fix: replace bare except clauses with except Exception Replace 44 bare statements across 14 files with . Bare except clauses catch SystemExit and KeyboardInterrupt which should propagate normally. This is a safe drop-in replacement that preserves existing error handling behavior while fixing the E722 lint violations. --- agentmain.py | 6 ++--- assets/code_run_header.py | 2 +- frontends/qtapp.py | 4 +-- frontends/stapp.py | 4 +-- frontends/stapp2.py | 4 +-- frontends/tgapp.py | 2 +- frontends/wechatapp.py | 2 +- ga.py | 16 ++++++------ llmcore.py | 32 +++++++++++------------ memory/autonomous_operation_sop/helper.py | 2 +- memory/ljqCtrl.py | 2 +- plugins/langfuse_tracing.py | 2 +- reflect/scheduler.py | 2 +- simphtml.py | 8 +++--- 14 files changed, 44 insertions(+), 44 deletions(-) diff --git a/agentmain.py b/agentmain.py index cf1d47c09..9122111d0 100644 --- a/agentmain.py +++ b/agentmain.py @@ -59,14 +59,14 @@ def load_llm_sessions(self): mykeys, changed = reload_mykeys() if not changed and hasattr(self, 'llmclients'): return try: oldhistory = self.llmclient.backend.history - except: oldhistory = None + except Exception: oldhistory = None llm_sessions = [] for k, cfg in mykeys.items(): if not any(x in k for x in ['api', 'config', 'cookie']): continue try: if 'mixin' in k: llm_sessions += [{'mixin_cfg': cfg}] elif c := resolve_client(k): llm_sessions += [c] - except: pass + except Exception: pass for i, s in enumerate(llm_sessions): if isinstance(s, dict) and 'mixin_cfg' in s: try: @@ -84,7 +84,7 @@ def next_llm(self, n=-1): lastc = self.llmclient self.llmclient = self.llmclients[self.llm_no] try: self.llmclient.backend.history = lastc.backend.history - except: raise Exception('[ERROR] BAD Mixin config: Check your mykey.py') + except Exception: raise Exception('[ERROR] BAD Mixin config: Check your mykey.py') self.llmclient.last_tools = '' name = self.get_llm_name(model=True) if 'glm' in name or 'minimax' in name or 'kimi' in name: load_tool_schema('_cn') diff --git a/assets/code_run_header.py b/assets/code_run_header.py index 59fb3416b..e7b268277 100644 --- a/assets/code_run_header.py +++ b/assets/code_run_header.py @@ -5,7 +5,7 @@ def _d(b): if not b: return '' if isinstance(b, str): return b try: return b.decode() - except: return b.decode('gbk', 'replace') + except Exception: return b.decode('gbk', 'replace') def _run(*a, **k): t = k.pop('text', 0) | k.pop('universal_newlines', 0) enc = k.pop('encoding', None) diff --git a/frontends/qtapp.py b/frontends/qtapp.py index 5e40a9c3f..0eb9c9fd3 100644 --- a/frontends/qtapp.py +++ b/frontends/qtapp.py @@ -707,7 +707,7 @@ def __init__(self, text: str, role: str, parent=None, on_resend=None, on_delete= time_lbl = QLabel(dt.strftime("%Y-%m-%d %H:%M")) time_lbl.setStyleSheet("color: #a1a1aa; font-size: 11px; background: transparent;") alayout.addWidget(time_lbl) - except: + except Exception: pass self._action_row.hide() @@ -791,7 +791,7 @@ def __init__(self, text: str, role: str, parent=None, on_resend=None, on_delete= time_lbl = QLabel(dt.strftime("%Y-%m-%d %H:%M")) time_lbl.setStyleSheet("color: #a1a1aa; font-size: 11px; background: transparent;") alayout.addWidget(time_lbl) - except: + except Exception: pass self._action_row.hide() diff --git a/frontends/stapp.py b/frontends/stapp.py index a19c134a1..173d8c74b 100644 --- a/frontends/stapp.py +++ b/frontends/stapp.py @@ -4,9 +4,9 @@ if sys.stdout is None: sys.stdout = open(os.devnull, "w") if sys.stderr is None: sys.stderr = open(os.devnull, "w") try: sys.stdout.reconfigure(errors='replace') -except: pass +except Exception: pass try: sys.stderr.reconfigure(errors='replace') -except: pass +except Exception: pass script_dir = os.path.dirname(__file__) sys.path.append(os.path.abspath(os.path.join(script_dir, '..'))) sys.path.append(os.path.abspath(script_dir)) diff --git a/frontends/stapp2.py b/frontends/stapp2.py index 1d7968f5d..47df57ae2 100644 --- a/frontends/stapp2.py +++ b/frontends/stapp2.py @@ -3,9 +3,9 @@ if sys.stdout is None: sys.stdout = open(os.devnull, "w") if sys.stderr is None: sys.stderr = open(os.devnull, "w") try: sys.stdout.reconfigure(errors='replace') -except: pass +except Exception: pass try: sys.stderr.reconfigure(errors='replace') -except: pass +except Exception: pass sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import streamlit as st diff --git a/frontends/tgapp.py b/frontends/tgapp.py index 0716af94b..8f0e09198 100644 --- a/frontends/tgapp.py +++ b/frontends/tgapp.py @@ -9,7 +9,7 @@ from telegram.ext import ApplicationBuilder, CallbackQueryHandler, MessageHandler, filters, ContextTypes from telegram.helpers import escape_markdown from telegram.request import HTTPXRequest -except: +except Exception: print("Please ask the agent install python-telegram-bot to use telegram module.") sys.exit(1) from chatapp_common import ( diff --git a/frontends/wechatapp.py b/frontends/wechatapp.py index aff57bf16..8b09c5f11 100644 --- a/frontends/wechatapp.py +++ b/frontends/wechatapp.py @@ -348,7 +348,7 @@ def _keep_typing(): if not ticket: return while not _typing_stop.is_set(): try: bot.send_typing(uid, ticket) - except: pass + except Exception: pass _typing_stop.wait(2.0) threading.Thread(target=_keep_typing, daemon=True).start() result = ''; sent = 0; mi = 0; last_send = 0; item = {} diff --git a/ga.py b/ga.py index 4ccd84f42..ffbd19d83 100644 --- a/ga.py +++ b/ga.py @@ -45,8 +45,8 @@ def stream_reader(proc, logs): except UnicodeDecodeError: line = line_bytes.decode('gbk', errors='ignore') logs.append(line) try: print(line, end="") - except: pass - except: pass + except Exception: pass + except Exception: pass try: process = subprocess.Popen( @@ -156,7 +156,7 @@ def log_memory_access(path): stats_file = os.path.join(script_dir, 'memory/file_access_stats.json') try: with open(stats_file, 'r', encoding='utf-8') as f: stats = json.load(f) - except: stats = {} + except Exception: stats = {} fname = os.path.basename(path) stats[fname] = {'count': stats.get(fname, {}).get('count', 0) + 1, 'last': datetime.now().strftime('%Y-%m-%d')} with open(stats_file, 'w', encoding='utf-8') as f: json.dump(stats, f, indent=2, ensure_ascii=False) @@ -286,7 +286,7 @@ def do_code_run(self, args, response): code = self._extract_code_block(response, code_type) if not code: return StepOutcome("[Error] Code missing. Must use reply code block or 'script' arg.", next_prompt="\n") try: timeout = int(args.get("timeout", 60)) - except: timeout = 60 + except Exception: timeout = 60 raw_path = os.path.join(self.cwd, args.get("cwd", './')) cwd = os.path.normpath(os.path.abspath(raw_path)) code_cwd = os.path.normpath(self.cwd) @@ -345,10 +345,10 @@ def do_web_execute_js(self, args, response): try: with open(abs_path, 'w', encoding='utf-8') as f: f.write(str(content)) result["js_return"] += f"\n\n[已保存完整内容到 {abs_path}]" - except: result['js_return'] += f"\n\n[保存失败,无法写入文件 {abs_path}]" + except Exception: result['js_return'] += f"\n\n[保存失败,无法写入文件 {abs_path}]" show = smart_format(json.dumps(result, ensure_ascii=False, indent=2, default=json_default), max_str_len=300) try: print("Web Execute JS Result:", show) - except: pass + except Exception: pass yield f"JS 执行结果:\n{show}\n" next_prompt = self._get_anchor_prompt(skip=args.get('_index', 0) > 0) result = json.dumps(result, ensure_ascii=False, default=json_default) @@ -430,7 +430,7 @@ def enter_plan_mode(self, plan_path): def _check_plan_completion(self): if not os.path.isfile(p:=self._in_plan_mode() or ''): return None try: return len(re.findall(r'\[ \]', open(p, encoding='utf-8', errors='replace').read())) - except: return None + except Exception: return None def do_update_working_checkpoint(self, args, response): '''为整个任务设定后续需要临时记忆的重点。''' @@ -541,7 +541,7 @@ def _get_anchor_prompt(self, skip=False): if self.working.get('related_sop'): prompt += f"\n有不清晰的地方请再次读取{self.working.get('related_sop')}" if getattr(self.parent, 'verbose', False): try: print(prompt) - except: pass + except Exception: pass return prompt def turn_end_callback(self, response, tool_calls, tool_results, turn, next_prompt, exit_reason): diff --git a/llmcore.py b/llmcore.py index 704874fd9..310a854d7 100644 --- a/llmcore.py +++ b/llmcore.py @@ -160,7 +160,7 @@ def _parse_claude_sse(resp_lines): if current_block: if current_block["type"] == "tool_use": try: current_block["input"] = json.loads(tool_json_buf) if tool_json_buf else {} - except: current_block["input"] = {"_raw": tool_json_buf} + except Exception: current_block["input"] = {"_raw": tool_json_buf} content_blocks.append(current_block) current_block = None elif evt_type == "message_delta": @@ -180,7 +180,7 @@ def _parse_claude_sse(resp_lines): if current_block: if current_block["type"] == "tool_use": try: current_block["input"] = json.loads(tool_json_buf) if tool_json_buf else {} - except: current_block["input"] = {"_raw": tool_json_buf} + except Exception: current_block["input"] = {"_raw": tool_json_buf} content_blocks.append(current_block); current_block = None if warn: print(f"[WARN] {warn.strip()}") @@ -192,13 +192,13 @@ def _try_parse_tool_args(raw): Returns list of parsed dicts.""" if not raw: return [{}] try: return [json.loads(raw)] - except: pass + except Exception: pass parts = re.split(r'(?<=\})(?=\{)', raw) if len(parts) > 1: parsed = [] for p in parts: try: parsed.append(json.loads(p)) - except: return [{"_raw": raw}] + except Exception: return [{"_raw": raw}] return parsed return [{"_raw": raw}] @@ -217,7 +217,7 @@ def _parse_openai_sse(resp_lines, api_mode="chat_completions"): data_str = line[5:].lstrip() if data_str == "[DONE]": break try: evt = json.loads(data_str) - except: continue + except Exception: continue etype = evt.get("type", "") if etype == "response.output_text.delta": delta = evt.get("delta", "") @@ -266,7 +266,7 @@ def _parse_openai_sse(resp_lines, api_mode="chat_completions"): data_str = line[5:].lstrip() if data_str == "[DONE]": break try: evt = json.loads(data_str) - except: continue + except Exception: continue ch = (evt.get("choices") or [{}])[0] delta = ch.get("delta") or {} if delta.get("reasoning_content"): @@ -323,7 +323,7 @@ def _parse_openai_json(data, api_mode="chat_completions"): blocks.append({"type": "text", "text": p["text"]}); yield p["text"] elif item.get("type") == "function_call": try: args = json.loads(item.get("arguments", "")) if item.get("arguments") else {} - except: args = {"_raw": item.get("arguments", "")} + except Exception: args = {"_raw": item.get("arguments", "")} blocks.append({"type": "tool_use", "id": item.get("call_id", item.get("id", "")), "name": item.get("name", ""), "input": args}) else: @@ -338,7 +338,7 @@ def _parse_openai_json(data, api_mode="chat_completions"): for tc in (msg.get("tool_calls") or []): fn = tc.get("function", {}) try: args = json.loads(fn.get("arguments", "")) if fn.get("arguments") else {} - except: args = {"_raw": fn.get("arguments", "")} + except Exception: args = {"_raw": fn.get("arguments", "")} blocks.append({"type": "tool_use", "id": tc.get("id", ""), "name": fn.get("name", ""), "input": args}) return blocks @@ -359,7 +359,7 @@ def _stream_with_retry(sess, url, headers, payload, parse_fn): _RETRYABLE = {408, 409, 425, 429, 500, 502, 503, 504, 529} def _delay(resp, attempt): try: ra = float((resp.headers or {}).get("retry-after")) - except: ra = None + except Exception: ra = None return max(0.5, ra if ra is not None else min(30.0, 1.5 * (2 ** attempt))) for attempt in range(sess.max_retries + 1): streamed = False @@ -372,7 +372,7 @@ def _delay(resp, attempt): print(f"[LLM Retry] HTTP {r.status_code}, retry in {d:.1f}s ({attempt+1}/{sess.max_retries+1})") time.sleep(d); continue try: body = r.text.strip()[:500] - except: body = "" + except Exception: body = "" err = f"!!!Error: HTTP {r.status_code}" + (f": {body}" if body else "") yield err; return [{"type": "text", "text": err}] gen = parse_fn(r) @@ -843,7 +843,7 @@ def _parse_mixed_response(self, text): except json.JSONDecodeError: errors.append(f'Failed to parse tool_use JSON: {json_str[:200]}') self.last_tools = '' - except: pass + except Exception: pass if not tool_calls: for e in errors: print(f"[Warn] {e}"); tool_calls.append(MockToolCall('bad_json', {'msg': e})) @@ -859,7 +859,7 @@ def _parse_text_tool_calls(content): idx = content.index(_jp); raw = json.loads(content[idx:]) tcs = [MockToolCall(b["name"], b.get("input", {}), id=b.get("id", "")) for b in raw if b.get("type") == "tool_use"] return tcs, content[:idx].strip() - except: pass + except Exception: pass # try XML tags: {"name":..., "arguments":...} _xp = r"<(?:tool_use|tool_call)>((?:(?!<(?:tool_use|tool_call)>).){15,}?)" for s in re.findall(_xp, content, re.DOTALL): @@ -867,7 +867,7 @@ def _parse_text_tool_calls(content): d = tryparse(s.strip()); name = d.get('name') args = d.get('arguments') or d.get('args') or d.get('input') or {} if name: tcs.append(MockToolCall(name, args)) - except: pass + except Exception: pass if tcs: content = re.sub(_xp, "", content, flags=re.DOTALL).strip() return tcs, content @@ -891,12 +891,12 @@ def _write_llm_log(label, content, log_path=None): def tryparse(json_str): try: return json.loads(json_str) - except: pass + except Exception: pass json_str = json_str.strip().strip('`').replace('json\n', '', 1).strip() try: return json.loads(json_str) - except: pass + except Exception: pass try: return json.loads(json_str[:-1]) - except: pass + except Exception: pass if '}' in json_str: json_str = json_str[:json_str.rfind('}') + 1] return json.loads(json_str) diff --git a/memory/autonomous_operation_sop/helper.py b/memory/autonomous_operation_sop/helper.py index 14a68a655..921c53ca3 100644 --- a/memory/autonomous_operation_sop/helper.py +++ b/memory/autonomous_operation_sop/helper.py @@ -114,7 +114,7 @@ def complete_task(taskname: str, historyline: str, report_path: str) -> str: # 回滚:把报告移回去 try: shutil.move(str(dest_path), str(report)) - except: + except Exception: pass return f"[ERROR] 写入 history 失败: {e}(报告已回滚)" diff --git a/memory/ljqCtrl.py b/memory/ljqCtrl.py index b68d98073..6ac41dc1f 100644 --- a/memory/ljqCtrl.py +++ b/memory/ljqCtrl.py @@ -17,7 +17,7 @@ try: from PIL import ImageGrab, Image, ImageEnhance, ImageFilter, ImageDraw import cv2 -except: pass +except Exception: pass _hdc = ctypes.windll.user32.GetDC(0) swidth = ctypes.windll.gdi32.GetDeviceCaps(_hdc, 118) # DESKTOPHORZRES (物理) diff --git a/plugins/langfuse_tracing.py b/plugins/langfuse_tracing.py index 3d503183a..687980116 100644 --- a/plugins/langfuse_tracing.py +++ b/plugins/langfuse_tracing.py @@ -104,7 +104,7 @@ def _extract_usage(buf): ds = s[5:].lstrip() if ds == '[DONE]': continue try: evt = _j.loads(ds) - except: continue + except Exception: continue if evt.get('type') == 'message_start': us = evt.get('message', {}).get('usage', {}) or {} u['input'] = us.get('input_tokens', u.get('input', 0)) diff --git a/reflect/scheduler.py b/reflect/scheduler.py index 28d701efc..b313bbb6b 100644 --- a/reflect/scheduler.py +++ b/reflect/scheduler.py @@ -56,7 +56,7 @@ def _last_run(tid, done_files): try: t = datetime.strptime(df[:15], '%Y-%m-%d_%H%M') if latest is None or t > latest: latest = t - except: continue + except Exception: continue return latest def check(): diff --git a/simphtml.py b/simphtml.py index cd4b87912..c1ad82ff4 100644 --- a/simphtml.py +++ b/simphtml.py @@ -635,7 +635,7 @@ def optimize_html_for_tokens(html): """ def start_temp_monitor(driver): try: driver.execute_js(temp_monitor_js) - except: pass + except Exception: pass def get_temp_texts(driver): js = """function stopStrMonitor() { @@ -821,7 +821,7 @@ def execute_js_rich(script, driver, no_monitor=False): last_html = None if not no_monitor: try: last_html = get_html(driver, cutlist=False, extra_js=temp_monitor_js, maxchars=9999999) - except: pass + except Exception: pass result = None; error_msg = None; reloaded = False; newTabs = [] before_sids = set(driver.get_session_dict().keys()); response = {} try: @@ -853,7 +853,7 @@ def execute_js_rich(script, driver, no_monitor=False): if no_monitor: return rr if not reloaded: try: rr['transients'] = get_temp_texts(driver) - except: rr['transients'] = [] + except Exception: rr['transients'] = [] if not reloaded and len(newTabs) == 0: try: current_html = get_html(driver, cutlist=False, maxchars=9999999) @@ -867,7 +867,7 @@ def execute_js_rich(script, driver, no_monitor=False): if change_count == 0 and not transients and len(newTabs) == 0: diff_summary += " (页面无变化)" rr['suggestion'] = "页面无明显变化" - except: + except Exception: diff_summary = "页面变化监控不可用" rr['diff'] = diff_summary return rr