如何自动找出VS Code工作区中未被调用的Python函数
自动检测VS Code工作区中未调用的Python函数
方法一:自定义Python脚本(精准可靠)
既然你假设项目无重名函数,用AST语法解析比正则更准确,不会误判注释或字符串里的函数定义。直接运行以下脚本,替换目标文件夹路径即可:
import ast import os from collections import defaultdict def find_dead_functions(root_dir): func_count = defaultdict(int) func_locations = {} for dirpath, _, filenames in os.walk(root_dir): for filename in filenames: if filename.endswith('.py'): file_path = os.path.join(dirpath, filename) try: with open(file_path, 'r', encoding='utf-8') as f: tree = ast.parse(f.read()) for node in ast.walk(tree): if isinstance(node, ast.FunctionDef): func_name = node.name func_count[func_name] += 1 if func_name not in func_locations: func_locations[func_name] = f"{file_path}:{node.lineno}" except Exception as e: print(f"处理文件失败 {file_path}: {e}") dead_functions = [ (name, loc) for name, count in func_count.items() if count == 1 ] return dead_functions if __name__ == "__main__": target_dir = "./your-workspace-folder" # 替换为你的目标路径 dead_funcs = find_dead_functions(target_dir) print("未被调用的死函数列表:") for name, loc in dead_funcs: print(f"- {name} | 定义位置:{loc}")
方法二:VS Code扩展(简单快捷)
直接在VS Code扩展市场搜索Dead Code Detector,安装后它会自动扫描工作区的Python文件,标记出未被调用的函数、类等死代码,支持一键定位查看,无需自己写代码。
方法三:命令行工具组合(快速临时检测)
用grep+sed+awk组合快速统计函数出现次数,筛选仅定义一次的函数:
# 替换./为你的目标文件夹路径 grep -r "^[\s]*def [a-zA-Z0-9_]*(" --include="*.py" ./ | sed 's/^[\s]*def \(.*\)(.*/\1/' | sort | uniq -c | awk '$1 == 1 {print $2}'
命令逻辑:
grep递归查找所有.py文件中的函数定义行sed提取每行的函数名sort+uniq -c统计每个函数名的出现次数awk筛选出仅出现一次的函数名
补充说明
删除死代码后,只需重新运行脚本或命令,就能再次检测新出现的死代码,彻底替代手动重复搜索的繁琐操作。
内容的提问来源于stack exchange,提问作者a.t.
相关产品推荐
相关产品推荐

