本文目录导读:

纯Bash脚本(推荐)
#!/bin/bash
# pip缓存清理脚本
# 功能:清理pip缓存目录释放磁盘空间
# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
echo -e "${BLUE}================================================${NC}"
echo -e "${BLUE} Pip缓存清理工具 v1.0${NC}"
echo -e "${BLUE}================================================${NC}"
# 获取缓存大小
get_cache_size() {
local cache_dir=$(pip cache dir 2>/dev/null || echo "~/.cache/pip")
if [ -d "$cache_dir" ]; then
du -sh "$cache_dir" 2>/dev/null | cut -f1
else
echo "0B"
fi
}
echo -e "${YELLOW}当前Pip缓存大小: $(get_cache_size)${NC}"
echo ""
# 显示选项
echo "请选择操作:"
echo "1. 完全清理所有pip缓存"
echo "2. 仅清理wheel缓存(保留索引缓存)"
echo "3. 查看缓存目录信息"
echo "4. 退出"
echo ""
read -p "请输入选项 (1-4): " choice
case $choice in
1)
echo -e "${YELLOW}正在清理所有pip缓存...${NC}"
pip cache purge
if [ $? -eq 0 ]; then
echo -e "${GREEN}✓ 清理完成!当前缓存大小: $(get_cache_size)${NC}"
else
echo -e "${RED}✗ 清理失败,请检查权限${NC}"
fi
;;
2)
echo -e "${YELLOW}正在清理wheel缓存...${NC}"
pip cache remove wheel
if [ $? -eq 0 ]; then
echo -e "${GREEN}✓ Wheel缓存已清理!当前缓存大小: $(get_cache_size)${NC}"
else
echo -e "${RED}✗ 清理失败,请检查权限${NC}"
fi
;;
3)
echo -e "${BLUE}缓存目录信息:${NC}"
echo -e " 缓存目录: $(pip cache dir 2>/dev/null || echo '~/.cache/pip')"
echo -e " 缓存大小: $(get_cache_size)"
echo -e " 缓存文件数: $(find $(pip cache dir 2>/dev/null || echo ~/.cache/pip) -type f 2>/dev/null | wc -l)"
;;
4)
echo -e "${YELLOW}退出清理程序${NC}"
exit 0
;;
*)
echo -e "${RED}无效选项,请重新运行脚本${NC}"
exit 1
;;
esac
Python脚本(跨平台)
#!/usr/bin/env python3
"""
自动清理pip缓存的Python脚本
支持Windows/Linux/Mac
"""
import os
import sys
import shutil
import subprocess
from pathlib import Path
import platform
class PipCacheCleaner:
def __init__(self):
self.system = platform.system()
self.cache_dirs = []
self.get_cache_dirs()
def get_cache_dirs(self):
"""获取pip缓存目录"""
# 尝试通过pip命令获取
try:
result = subprocess.run(
[sys.executable, '-m', 'pip', 'cache', 'dir'],
capture_output=True, text=True
)
if result.returncode == 0:
self.cache_dirs.append(Path(result.stdout.strip()))
except:
pass
# 默认缓存目录
home = Path.home()
if self.system == "Windows":
default_dirs = [
home / 'AppData' / 'Local' / 'pip' / 'cache',
home / 'AppData' / 'Roaming' / 'pip' / 'cache',
Path(os.environ.get('LOCALAPPDATA', '')) / 'pip' / 'cache'
]
elif self.system == "Darwin": # macOS
default_dirs = [
home / 'Library' / 'Caches' / 'pip',
home / '.cache' / 'pip'
]
else: # Linux
default_dirs = [
home / '.cache' / 'pip',
Path('/tmp') / 'pip-cache'
]
for dir_path in default_dirs:
if dir_path not in self.cache_dirs and dir_path.exists():
self.cache_dirs.append(dir_path)
def get_cache_size(self):
"""获取缓存总大小"""
total_size = 0
for cache_dir in self.cache_dirs:
if cache_dir.exists():
for f in cache_dir.rglob('*'):
if f.is_file():
try:
total_size += f.stat().st_size
except:
pass
return total_size
def format_size(self, size_bytes):
"""格式化文件大小"""
for unit in ['B', 'KB', 'MB', 'GB']:
if size_bytes < 1024.0:
return f"{size_bytes:.2f} {unit}"
size_bytes /= 1024.0
return f"{size_bytes:.2f} TB"
def clean_all(self):
"""完全清理所有缓存"""
print("正在清理所有pip缓存...")
# 方法1:使用pip命令
try:
subprocess.run(
[sys.executable, '-m', 'pip', 'cache', 'purge'],
check=True
)
print("✓ 通过pip命令清理完成")
except Exception as e:
print(f" pip命令清理失败: {e}")
# 方法2:手动删除目录
for cache_dir in self.cache_dirs:
if cache_dir.exists():
try:
shutil.rmtree(cache_dir)
print(f" ✓ 删除目录: {cache_dir}")
except Exception as e:
print(f" ✗ 删除失败 {cache_dir}: {e}")
print("清理完成!")
def clean_wheels(self):
"""仅清理wheel缓存"""
print("正在清理wheel缓存...")
for cache_dir in self.cache_dirs:
if cache_dir.exists():
wheels_dir = cache_dir / 'wheels'
if wheels_dir.exists():
try:
shutil.rmtree(wheels_dir)
print(f" ✓ 清理wheel目录: {wheels_dir}")
except Exception as e:
print(f" ✗ 清理失败: {e}")
print("Wheel缓存清理完成!")
def show_info(self):
"""显示缓存信息"""
print("=" * 50)
print(f"Pip缓存清理工具 - {self.system}")
print("=" * 50)
print(f"\n当前缓存目录:")
for cache_dir in self.cache_dirs:
status = "✓ 存在" if cache_dir.exists() else "✗ 不存在"
print(f" - {cache_dir} [{status}]")
total_size = self.get_cache_size()
print(f"\n缓存总大小: {self.format_size(total_size)}")
# 列出各目录大小
for cache_dir in self.cache_dirs:
if cache_dir.exists():
size = sum(f.stat().st_size for f in cache_dir.rglob('*') if f.is_file())
print(f" {cache_dir}: {self.format_size(size)}")
def run(self):
"""主运行函数"""
self.show_info()
print("\n请选择操作:")
print("1. 完全清理所有pip缓存")
print("2. 仅清理wheel缓存(保留索引缓存)")
print("3. 查看缓存目录信息")
print("4. 退出")
try:
choice = input("\n请输入选项 (1-4): ").strip()
if choice == '1':
self.clean_all()
elif choice == '2':
self.clean_wheels()
elif choice == '3':
self.show_info()
elif choice == '4':
print("退出清理程序")
sys.exit(0)
else:
print("无效选项!")
sys.exit(1)
except KeyboardInterrupt:
print("\n用户中断操作")
sys.exit(0)
except Exception as e:
print(f"发生错误: {e}")
sys.exit(1)
if __name__ == "__main__":
cleaner = PipCacheCleaner()
cleaner.run()
定时自动清理(Linux/Mac)
创建一个cron任务定期清理:
#!/bin/bash # 创建每周自动清理的cron任务 # 1. 创建清理脚本 cat > /tmp/auto_clean_pip_cache.sh << 'EOF' #!/bin/bash # 自动清理pip缓存(保留最近7天的缓存) pip cache purge 2>/dev/null || true # 清理pip缓存目录中超过7天的文件 find ~/.cache/pip -type f -mtime +7 -delete 2>/dev/null # 清理空目录 find ~/.cache/pip -type d -empty -delete 2>/dev/null EOF chmod +x /tmp/auto_clean_pip_cache.sh sudo mv /tmp/auto_clean_pip_cache.sh /usr/local/bin/auto_clean_pip_cache.sh # 2. 添加cron任务(每周日清理) (crontab -l 2>/dev/null; echo "0 3 * * 0 /usr/local/bin/auto_clean_pip_cache.sh") | crontab - echo "✓ 已创建每周自动清理任务"
使用方法
- Bash脚本:保存为
clean_pip_cache.sh,运行bash clean_pip_cache.sh - Python脚本:保存为
clean_pip_cache.py,运行python clean_pip_cache.py - 定时任务:运行脚本自动创建定时清理任务
注意事项
- 清理缓存后下次安装包时会重新下载,但可以确保磁盘空间充足
- 建议保留部分缓存以提高安装速度(可以使用
pip cache remove wheel仅清理wheel文件) - 如果磁盘空间紧张,可以设置每月自动清理一次
- Windows用户建议使用Python脚本版本
选择适合你需求的脚本即可!