54 lines
1.8 KiB
Python
54 lines
1.8 KiB
Python
import os
|
|
import pkgutil
|
|
import fileinput
|
|
import sys
|
|
|
|
def replace_keyword_in_package_file(package_name, target_file, old_str, new_str):
|
|
"""
|
|
替换指定包中某个文件的关键字
|
|
|
|
参数:
|
|
package_name (str): 要查找的包名
|
|
target_file (str): 要替换的文件名(包括相对路径)
|
|
old_str (str): 要被替换的关键字
|
|
new_str (str): 替换后的新关键字
|
|
"""
|
|
try:
|
|
# 获取包的路径
|
|
package = pkgutil.get_loader(package_name)
|
|
if package is None:
|
|
print(f"错误: 找不到包 '{package_name}'")
|
|
return False
|
|
|
|
package_path = os.path.dirname(package.get_filename())
|
|
target_path = os.path.join(package_path, target_file)
|
|
|
|
# 检查目标文件是否存在
|
|
if not os.path.exists(target_path):
|
|
print(f"错误: 文件 '{target_file}' 不在包 '{package_name}' 的路径中")
|
|
return False
|
|
|
|
# 执行替换操作
|
|
print(f"正在处理文件: {target_path}")
|
|
print(f"将 '{old_str}' 替换为 '{new_str}'")
|
|
|
|
replaced = False
|
|
with fileinput.FileInput(target_path, inplace=True, backup='.bak') as file:
|
|
for line in file:
|
|
if old_str in line:
|
|
replaced = True
|
|
print(line.replace(old_str, new_str), end='')
|
|
|
|
if replaced:
|
|
print("替换完成!")
|
|
return True
|
|
else:
|
|
print(f"警告: 文件中未找到关键字 '{old_str}'")
|
|
return False
|
|
|
|
except Exception as e:
|
|
print(f"发生错误: {str(e)}")
|
|
return False
|
|
|
|
replace_keyword_in_package_file("aioredis", "exceptions.py", "builtins.TimeoutError,", "")
|