#!/usr/bin/env python3 """ 智能修复 Python 文件中的缩进语法错误 ===================================== 使用 AST 和 tokenize 来更准确地修复缩进问题 """ import ast import tokenize import io import sys from typing import List, Tuple, Optional def analyze_indentation_errors(file_path: str) -> List[Tuple[int, str, str]]: """分析文件中的缩进错误 返回: [(行号, 错误类型, 建议修复)] """ errors = [] try: with open(file_path, 'rb') as f: tokens = list(tokenize.tokenize(f.readline)) except Exception as e: return [(-1, "读取文件失败", str(e))] # 分析 try-except 块 try_blocks = [] for i, token in enumerate(tokens): if token.type == tokenize.NAME and token.string == 'try': # 查找对应的 except try_indent = token.start[1] # 列号 try_blocks.append((token.start[0], try_indent)) # (行号, 缩进) # 检查 except 是否与对应的 try 对齐 for try_line, try_indent in try_blocks: # 查找这个 try 后面的 except for i, token in enumerate(tokens): if (token.type == tokenize.NAME and token.string == 'except' and token.start[0] > try_line): except_indent = token.start[1] if except_indent != try_indent: errors.append(( token.start[0], "except 缩进错误", f"应该与 try (第 {try_line} 行) 对齐,当前缩进 {except_indent},应为 {try_indent}" )) break return errors def fix_indentation_with_ast(file_path: str) -> Tuple[bool, str]: """使用 AST 尝试修复缩进错误""" try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # 尝试解析 try: ast.parse(content) return True, "文件语法正确" except SyntaxError as e: # 有语法错误,尝试修复 lines = content.split('\n') # 修复常见的 except 缩进错误 fixed_lines = [] for i, line in enumerate(lines): # 检查是否是 except 语句且缩进可能有问题 if re.match(r'^\s{8,}except\s+', line): # 向前查找 try for j in range(i-1, max(-1, i-30), -1): if re.match(r'^(\s*)try\s*:', lines[j]): try_indent = len(re.match(r'^(\s*)', lines[j]).group(1)) # 修复缩进 fixed_line = ' ' * try_indent + line.lstrip() fixed_lines.append(fixed_line) break else: fixed_lines.append(line) else: fixed_lines.append(line) fixed_content = '\n'.join(fixed_lines) # 验证修复 try: ast.parse(fixed_content) with open(file_path, 'w', encoding='utf-8') as f: f.write(fixed_content) return True, "修复成功" except SyntaxError: return False, "无法自动修复" except Exception as e: return False, f"错误: {e}" if __name__ == '__main__': import re if len(sys.argv) < 2: print("使用方法: python fix_indent_smart.py <文件路径>") sys.exit(1) file_path = sys.argv[1] success, msg = fix_indentation_with_ast(file_path) print(msg)