Files
change_hair/fix_conda_paths.py
T
2026-07-17 22:13:56 +08:00

70 lines
2.5 KiB
Python

#!/usr/bin/env python3
"""安全修复 conda 环境内的硬编码路径前缀。
只处理文本文件(通过二进制检测),跳过 .so/.pyc/权重等二进制文件。
"""
import os
import sys
OLD_PREFIXES = [
b"/home/szlc/miniconda3",
b"/usr/local/miniconda3",
]
NEW_PREFIX = b"/home/ubuntu/miniconda3"
def is_probably_binary(filepath):
"""通过文件扩展名和内容判断是否为二进制文件"""
# 明确的文本扩展名直接处理
text_exts = ('.py', '.sh', '.txt', '.cfg', '.ini', '.json', '.yaml', '.yml',
'.cmake', '.make', '.pc', '.la', '.template', '.desktop',
'.service', '.conf', '.md', '.rst', '.in', '.bashrc', '.profile')
binary_exts = ('.so', '.pyc', '.pyo', '.a', '.o', '.dylib', '.dll',
'.pth', '.pt', '.bin', '.safetensors', '.ckpt', '.npz',
'.npy', '.pkl', '.zip', '.tar', '.gz', '.bz2', '.png',
'.jpg', '.jpeg', '.woff', '.ttf', '.eot', '.ico')
if filepath.endswith(binary_exts):
return True
if filepath.endswith(text_exts):
return False
# 无明确扩展名:读取前 8KB 检测是否含 null 字节
try:
with open(filepath, 'rb') as f:
chunk = f.read(8192)
return b'\x00' in chunk
except Exception:
return True
def fix_env(env_dir):
fixed = 0
scanned = 0
for root, dirs, files in os.walk(env_dir):
# 跳过明显的二进制/缓存目录
dirs[:] = [d for d in dirs if d not in ('__pycache__', '.git')]
for fname in files:
fpath = os.path.join(root, fname)
scanned += 1
try:
if is_probably_binary(fpath):
continue
with open(fpath, 'rb') as f:
content = f.read()
original = content
for old in OLD_PREFIXES:
content = content.replace(old, NEW_PREFIX)
if content != original:
with open(fpath, 'wb') as f:
f.write(content)
fixed += 1
except (PermissionError, OSError):
continue
print(f" 扫描 {scanned} 文件, 修改 {fixed} 文件")
return fixed
if __name__ == "__main__":
for env in sys.argv[1:]:
env_path = f"/home/ubuntu/miniconda3/envs/{env}"
if os.path.isdir(env_path):
print(f"[{env}] 修复中...")
fix_env(env_path)
else:
print(f"[{env}] 目录不存在,跳过")