如何批量修改多Python文件中的函数名与参数名?
批量修改Python文件中的函数名与参数名的实现方法
当然有,这里提供两种实用方法,分别适用于不同场景:
方法一:用AST抽象语法树精准修改(推荐)
这种方法通过解析代码的语法结构来修改,不会误改字符串、注释里的内容,适合复杂代码场景。
首先安装依赖:
pip install astunparse
然后运行以下脚本,它会遍历指定目录下所有.py文件,完成函数名和参数名的替换:
import ast import os import astunparse # 定义替换规则:原名称 -> 新名称 FUNC_REPLACEMENTS = {"sum": "new_name"} PARAM_REPLACEMENTS = {"b": "c"} def traverse_and_modify(node): # 修改函数定义的名称 if isinstance(node, ast.FunctionDef) and node.name in FUNC_REPLACEMENTS: node.name = FUNC_REPLACEMENTS[node.name] # 修改函数参数名 if isinstance(node, ast.FunctionDef): for arg in node.args.args: if arg.arg in PARAM_REPLACEMENTS: arg.arg = PARAM_REPLACEMENTS[arg.arg] # 修改函数调用的名称 if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in FUNC_REPLACEMENTS: node.func.id = FUNC_REPLACEMENTS[node.func.id] # 修改表达式中的变量名(比如2*b里的b) if isinstance(node, ast.Name) and node.id in PARAM_REPLACEMENTS: node.id = PARAM_REPLACEMENTS[node.id] # 递归处理所有子节点 for child in ast.iter_child_nodes(node): traverse_and_modify(child) def process_single_file(file_path): with open(file_path, "r", encoding="utf-8") as f: raw_code = f.read() try: # 解析代码为语法树 code_tree = ast.parse(raw_code) traverse_and_modify(code_tree) # 生成修改后的代码并格式化 modified_code = astunparse.unparse(code_tree) # 清理多余空行 modified_code = "\n".join(line for line in modified_code.splitlines() if line.strip()) with open(file_path, "w", encoding="utf-8") as f: f.write(modified_code) print(f"✅ 处理完成:{file_path}") except Exception as e: print(f"❌ 处理{file_path}失败:{str(e)}") def process_directory(target_dir): for root, _, files in os.walk(target_dir): for file in files: if file.endswith(".py"): process_single_file(os.path.join(root, file)) if __name__ == "__main__": # 处理当前目录下所有.py文件,可替换为你的目标目录路径 process_directory(".")
方法二:用正则表达式快速替换(简单场景)
如果你的代码结构简单,没有字符串、注释干扰,可以用正则快速批量替换,缺点是可能误改非代码内容:
import os import re # 替换规则:正则匹配模式 -> 替换内容 REPLACE_RULES = [ (r"\bsum\b", "new_name"), # 匹配独立的sum单词 (r"\bb\b", "c") # 匹配独立的b单词 ] def process_file(file_path): with open(file_path, "r", encoding="utf-8") as f: content = f.read() for pattern, repl in REPLACE_RULES: content = re.sub(pattern, repl, content) with open(file_path, "w", encoding="utf-8") as f: f.write(content) print(f"✅ 处理完成:{file_path}") def process_dir(target_dir): for root, _, files in os.walk(target_dir): for file in files: if file.endswith(".py"): process_file(os.path.join(root, file)) if __name__ == "__main__": process_dir(".")
注意事项
- 操作前务必备份所有.py文件,避免意外问题
- AST方法更可靠,推荐优先使用;正则仅适合代码无干扰内容的场景
内容的提问来源于stack exchange,提问作者Sadcow
相关产品推荐
相关产品推荐

