#!/usr/bin/env python # -*- coding: utf-8 -*- """ 检查 ARTv2 核心代码中的关键变量作用域问题 专注于 except 块中的变量作用域问题 """ import os import re def check_except_variable_usage(file_path): """ 检查 except 块中定义的变量在块外使用的问题 这是最常见和最危险的作用域问题 """ issues = [] with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: lines = f.readlines() i = 0 while i < len(lines): line = lines[i] # 查找 except Exception as X: 模式 match = re.match(r'^(\s*)except\s+\w+\s+as\s+(\w+):', line) if match: except_indent = len(match.group(1)) except_var = match.group(2) except_line = i + 1 # 找到 except 块的结束位置 j = i + 1 except_end = j while j < len(lines): next_line = lines[j] if next_line.strip(): next_indent = len(next_line) - len(next_line.lstrip()) if next_indent <= except_indent: except_end = j break j += 1 # 检查 except 块之后的代码是否使用了异常变量 for k in range(except_end, min(len(lines), except_end + 50)): check_line = lines[k] if check_line.strip() and not check_line.strip().startswith('#'): # 检查是否使用了异常变量 if re.search(r'\b' + except_var + r'\b', check_line): # 确保不是在新的 except 块中 if not re.match(r'^\s*except.*as\s+' + except_var, check_line): issues.append({ 'except_line': except_line, 'usage_line': k + 1, 'except_code': line.rstrip(), 'usage_code': check_line.rstrip(), 'variable': except_var }) break i = except_end else: i += 1 return issues def main(): """主函数""" script_dir = os.path.dirname(os.path.abspath(__file__)) # 只检查核心 ARTv2 代码,排除第三方库 check_dirs = [ os.path.join(script_dir, 'Core', 'Scripts', 'Interfaces'), os.path.join(script_dir, 'Core', 'Scripts', 'RigModules'), os.path.join(script_dir, 'Core', 'Scripts', 'System'), ] print("=" * 70) print("ARTv2 核心代码 - 异常变量作用域检查") print("=" * 70) print() total_files = 0 total_issues = 0 issue_files = [] for check_dir in check_dirs: if not os.path.exists(check_dir): continue for root, dirs, files in os.walk(check_dir): for filename in files: if filename.endswith('.py'): total_files += 1 file_path = os.path.join(root, filename) rel_path = os.path.relpath(file_path, script_dir) issues = check_except_variable_usage(file_path) if issues: total_issues += len(issues) issue_files.append((rel_path, issues)) if issue_files: print(f"⚠️ 发现 {total_issues} 个异常变量作用域问题:\n") for file_path, issues in issue_files: print(f"📁 {file_path}") for issue in issues: print(f" Except 块: Line {issue['except_line']}") print(f" {issue['except_code']}") print(f" ❌ 变量 '{issue['variable']}' 在块外使用: Line {issue['usage_line']}") print(f" {issue['usage_code'][:70]}") print() print("=" * 70) print(f"检查完成: 扫描了 {total_files} 个核心文件") if total_issues == 0: print("✅ 未发现异常变量作用域问题") else: print(f"❌ 发现 {total_issues} 个需要修复的问题") print("=" * 70) if __name__ == '__main__': main()