Python指定IF代码块移除脚本故障排查与修正需求
修正批量移除指定IF条件代码块的Python脚本
原脚本误删连续IF块的核心问题是未正确跟踪缩进层级,导致无法区分不同IF块的边界。以下是修正后的实现,精准匹配目标IF块并仅删除其包含的缩进内容:
修正后的脚本
import os import re def remove_target_if_blocks(file_path, target_pattern=r'if\s+(app\.)?ENABLE_[A-Z_]+:'): """移除文件中匹配指定模式的IF条件代码块(含缩进内容)""" with open(file_path, 'r', encoding='utf-8') as f: lines = f.readlines() output_lines = [] in_delete_block = False base_indent = 0 # 记录目标IF行的缩进层级 for line in lines: stripped_line = line.strip() # 保留空行(可根据需求移除该判断) if not stripped_line: output_lines.append(line) continue # 计算当前行缩进(空格缩进,tab缩进需替换为lstrip('\t')) current_indent = len(line) - len(line.lstrip(' ')) # 匹配目标IF行,标记进入删除块 if re.match(target_pattern, stripped_line): in_delete_block = True base_indent = current_indent continue # 处于删除块时,判断是否退出块 if in_delete_block: if current_indent <= base_indent: in_delete_block = False output_lines.append(line) continue # 非目标块内容直接保留 output_lines.append(line) # 写回文件(务必先备份原文件) with open(file_path, 'w', encoding='utf-8') as f: f.writelines(output_lines) def batch_process_files(root_dir, target_pattern=r'if\s+(app\.)?ENABLE_[A-Z_]+:'): """批量处理目录下所有.py文件""" for dirpath, _, filenames in os.walk(root_dir): for filename in filenames: if filename.endswith('.py'): file_path = os.path.join(dirpath, filename) print(f"Processing {file_path}...") remove_target_if_blocks(file_path, target_pattern) if __name__ == '__main__': # 替换为你的代码目录路径 target_directory = './your_python_code_dir' batch_process_files(target_directory)
关键逻辑说明
- 缩进层级跟踪:通过计算每行前置空格数确定缩进,精准识别IF块的边界,避免误删相邻IF块
- 状态标记:用
in_delete_block控制是否处于删除状态,只有当后续行缩进回到目标IF行的层级时,才退出删除模式 - 灵活匹配:正则表达式支持匹配
if ENABLE_*:和if app.ENABLE_*:两种格式,可根据需求调整匹配规则 - 格式保留:保留空行和非目标代码的原有格式,避免破坏代码结构
使用注意事项
- 执行前务必备份原代码,防止意外数据丢失
- 若代码使用tab缩进,需将缩进计算部分的
lstrip(' ')替换为lstrip('\t') - 可修改
target_pattern正则,匹配特定的IF条件(例如仅删除if app.ENABLE_GROWTH_PET_SYSTEM:)
内容的提问来源于stack exchange,提问作者xapi
相关产品推荐
相关产品推荐

