#!/usr/bin/env python3 """ 批量修复 Python 文件中的缩进语法错误 ===================================== 这个脚本可以修复常见的缩进导致的语法错误: 1. except 语句缩进错误 2. else 语句缩进错误 3. finally 语句缩进错误 4. 其他常见的缩进问题 使用方法: python fix_indentation.py <文件路径> python fix_indentation.py --all # 修复当前目录下所有 .py 文件 """ import re import sys import os from pathlib import Path from typing import List, Tuple def fix_except_indentation(content: str) -> str: """修复 except 语句的缩进错误""" lines = content.split('\n') fixed_lines = [] i = 0 while i < len(lines): line = lines[i] # 检查是否有缩进错误的 except # 模式:行首有空格,但 except 前面有额外的缩进 if re.match(r'^\s{4,}except\s+', line): # 检查前一行是否是 try 块 if i > 0: prev_line = lines[i-1].rstrip() # 查找对应的 try 语句 try_indent = None for j in range(i-1, max(-1, i-20), -1): # 向前查找最多20行 if re.match(r'^(\s*)try\s*:', lines[j]): try_indent = len(re.match(r'^(\s*)', lines[j]).group(1)) break if try_indent is not None: # 修复缩进:except 应该和 try 对齐 fixed_line = ' ' * try_indent + line.lstrip() fixed_lines.append(fixed_line) i += 1 continue fixed_lines.append(line) i += 1 return '\n'.join(fixed_lines) def fix_else_indentation(content: str) -> str: """修复 else 语句的缩进错误""" lines = content.split('\n') fixed_lines = [] i = 0 while i < len(lines): line = lines[i] # 检查是否有缩进错误的 else if re.match(r'^\s{4,}else\s*:', line): # 查找对应的 if/for/while/try 语句 if_indent = None for j in range(i-1, max(-1, i-50), -1): # 向前查找 prev_line = lines[j].rstrip() if prev_line and not prev_line.strip().startswith('#'): # 检查是否是 if/for/while/try 语句 if re.match(r'^(\s*)(if|for|while|try|elif)\s+.*:', prev_line): if_indent = len(re.match(r'^(\s*)', prev_line).group(1)) break if if_indent is not None: # 修复缩进:else 应该和 if/for/while/try 对齐 fixed_line = ' ' * if_indent + line.lstrip() fixed_lines.append(fixed_line) i += 1 continue fixed_lines.append(line) i += 1 return '\n'.join(fixed_lines) def fix_common_indentation_errors(content: str) -> str: """修复常见的缩进错误模式""" # 修复模式1: except Exception: 前面有多余缩进 # 从: " except Exception:" # 到: " except Exception:" (与对应的 try 对齐) content = re.sub( r'^(\s{8,})except\s+', lambda m: ' ' * (len(m.group(1)) - 4) + 'except ', content, flags=re.MULTILINE ) # 修复模式2: else: 前面有多余缩进 content = re.sub( r'^(\s{8,})else\s*:', lambda m: ' ' * (len(m.group(1)) - 4) + 'else:', content, flags=re.MULTILINE ) # 修复模式3: finally: 前面有多余缩进 content = re.sub( r'^(\s{8,})finally\s*:', lambda m: ' ' * (len(m.group(1)) - 4) + 'finally:', content, flags=re.MULTILINE ) return content def fix_file(file_path: str, dry_run: bool = False) -> Tuple[bool, str]: """修复单个文件的缩进错误 返回: (是否成功, 错误信息) """ try: with open(file_path, 'r', encoding='utf-8') as f: original_content = f.read() # 先尝试用 Python 解析,如果成功则不需要修复 try: compile(original_content, file_path, 'exec') return True, "文件语法正确,无需修复" except SyntaxError: pass # 有语法错误,继续修复 # 应用修复 fixed_content = original_content fixed_content = fix_except_indentation(fixed_content) fixed_content = fix_else_indentation(fixed_content) fixed_content = fix_common_indentation_errors(fixed_content) # 验证修复后的代码 try: compile(fixed_content, file_path, 'exec') if not dry_run: with open(file_path, 'w', encoding='utf-8') as f: f.write(fixed_content) return True, "修复成功" if not dry_run else "可以修复(预览模式)" except SyntaxError as e: return False, f"修复后仍有语法错误: {e}" except Exception as e: return False, f"处理文件时出错: {e}" def main(): """主函数""" if len(sys.argv) < 2: print("使用方法:") print(" python fix_indentation.py <文件路径>") print(" python fix_indentation.py --all [目录路径]") print(" python fix_indentation.py --dry-run <文件路径> # 预览模式,不实际修改") sys.exit(1) dry_run = '--dry-run' in sys.argv if dry_run: sys.argv.remove('--dry-run') if sys.argv[1] == '--all': # 修复目录下所有 .py 文件 target_dir = sys.argv[2] if len(sys.argv) > 2 else '.' py_files = list(Path(target_dir).rglob('*.py')) print(f"找到 {len(py_files)} 个 Python 文件") success_count = 0 fail_count = 0 for py_file in py_files: # 跳过虚拟环境和缓存目录 if any(skip in str(py_file) for skip in ['__pycache__', '.venv', 'venv', '.git']): continue print(f"处理: {py_file}") success, msg = fix_file(str(py_file), dry_run=dry_run) if success: print(f" ✓ {msg}") success_count += 1 else: print(f" ✗ {msg}") fail_count += 1 print(f"\n完成: 成功 {success_count} 个,失败 {fail_count} 个") else: # 修复单个文件 file_path = sys.argv[1] if not os.path.exists(file_path): print(f"错误: 文件不存在: {file_path}") sys.exit(1) print(f"处理文件: {file_path}") success, msg = fix_file(file_path, dry_run=dry_run) if success: print(f"✓ {msg}") else: print(f"✗ {msg}") sys.exit(1) if __name__ == '__main__': main()