94 lines
2.9 KiB
Python
94 lines
2.9 KiB
Python
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
检查 ARTv2 代码中的异常变量作用域问题
|
|
"""
|
|
|
|
import os
|
|
import re
|
|
|
|
def check_exception_scope(file_path):
|
|
"""检查文件中的异常变量作用域问题"""
|
|
issues = []
|
|
|
|
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
|
|
lines = f.readlines()
|
|
|
|
in_except = False
|
|
except_var = None
|
|
except_indent = 0
|
|
|
|
for i, line in enumerate(lines, 1):
|
|
# 计算缩进
|
|
stripped = line.lstrip()
|
|
if not stripped or stripped.startswith('#'):
|
|
continue
|
|
|
|
indent = len(line) - len(stripped)
|
|
|
|
# 检测 except 块
|
|
match = re.match(r'except\s+\w+\s+as\s+(\w+):', stripped)
|
|
if match:
|
|
in_except = True
|
|
except_var = match.group(1)
|
|
except_indent = indent
|
|
continue
|
|
|
|
# 检测是否退出 except 块
|
|
if in_except and stripped and indent <= except_indent:
|
|
# 检查这一行是否使用了异常变量
|
|
if except_var and re.search(r'\b' + except_var + r'\b', stripped):
|
|
# 排除注释和新的 except 语句
|
|
if not stripped.startswith('#') and not stripped.startswith('except'):
|
|
issues.append({
|
|
'line': i,
|
|
'code': line.rstrip(),
|
|
'variable': except_var
|
|
})
|
|
in_except = False
|
|
except_var = None
|
|
|
|
return issues
|
|
|
|
def main():
|
|
"""主函数"""
|
|
script_dir = os.path.dirname(os.path.abspath(__file__))
|
|
core_scripts = os.path.join(script_dir, 'Core', 'Scripts')
|
|
|
|
print("=" * 70)
|
|
print("ARTv2 异常变量作用域检查")
|
|
print("=" * 70)
|
|
print()
|
|
|
|
total_files = 0
|
|
total_issues = 0
|
|
|
|
for root, dirs, files in os.walk(core_scripts):
|
|
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_exception_scope(file_path)
|
|
|
|
if issues:
|
|
total_issues += len(issues)
|
|
print(f"⚠️ {rel_path}")
|
|
print(f" 发现 {len(issues)} 个潜在问题:")
|
|
for issue in issues:
|
|
print(f" Line {issue['line']}: {issue['code']}")
|
|
print(f" 变量 '{issue['variable']}' 可能在 except 块外使用")
|
|
print()
|
|
|
|
print("=" * 70)
|
|
print(f"检查完成: 扫描了 {total_files} 个文件")
|
|
if total_issues == 0:
|
|
print("✅ 未发现异常变量作用域问题")
|
|
else:
|
|
print(f"⚠️ 发现 {total_issues} 个潜在问题")
|
|
print("=" * 70)
|
|
|
|
if __name__ == '__main__':
|
|
main()
|