Python脚本如何批量删除指定缓存

wen python案例 26

本文目录导读:

Python脚本如何批量删除指定缓存

  1. 删除特定目录下的缓存文件
  2. 删除浏览器缓存
  3. 删除系统临时文件
  4. 删除Python项目中的缓存
  5. 综合缓存清理工具
  6. 使用注意事项

删除特定目录下的缓存文件

import os
import shutil
from pathlib import Path
def delete_cache_files(directory, patterns=None):
    """
    批量删除缓存文件
    :param directory: 目标目录
    :param patterns: 要删除的文件模式列表,如 ['*.pyc', '__pycache__']
    """
    if patterns is None:
        patterns = ['*.pyc', '*.pyo', '__pycache__', '.DS_Store', 'Thumbs.db']
    deleted_count = 0
    for pattern in patterns:
        if '*' in pattern:
            # 删除匹配的文件模式
            for file_path in Path(directory).rglob(pattern):
                try:
                    if file_path.is_file():
                        file_path.unlink()
                        print(f"删除文件: {file_path}")
                        deleted_count += 1
                except Exception as e:
                    print(f"删除失败 {file_path}: {e}")
        else:
            # 删除特定目录名
            for dir_path in Path(directory).rglob(pattern):
                try:
                    if dir_path.is_dir():
                        shutil.rmtree(dir_path)
                        print(f"删除目录: {dir_path}")
                        deleted_count += 1
                except Exception as e:
                    print(f"删除失败 {dir_path}: {e}")
    print(f"共删除 {deleted_count} 个缓存对象")
    return deleted_count
# 使用示例
delete_cache_files("./project")

删除浏览器缓存

import os
import glob
import shutil
def delete_browser_cache(browser_type='all'):
    """
    删除浏览器缓存
    :param browser_type: 'chrome', 'firefox', 'edge', 'all'
    """
    # 获取用户主目录
    home = os.path.expanduser("~")
    browsers = {
        'chrome': {
            'windows': os.path.join(os.getenv('LOCALAPPDATA'), 'Google', 'Chrome', 'User Data', 'Default', 'Cache'),
            'mac': os.path.join(home, 'Library', 'Caches', 'Google', 'Chrome'),
            'linux': os.path.join(home, '.cache', 'google-chrome')
        },
        'firefox': {
            'windows': os.path.join(os.getenv('APPDATA'), 'Mozilla', 'Firefox', 'Profiles'),
            'mac': os.path.join(home, 'Library', 'Caches', 'Firefox'),
            'linux': os.path.join(home, '.cache', 'mozilla', 'firefox')
        },
        'edge': {
            'windows': os.path.join(os.getenv('LOCALAPPDATA'), 'Microsoft', 'Edge', 'User Data', 'Default', 'Cache'),
            'mac': os.path.join(home, 'Library', 'Caches', 'Microsoft Edge'),
        }
    }
    # 检测操作系统
    import platform
    system = platform.system().lower()
    if system == 'darwin':
        os_name = 'mac'
    elif system == 'windows':
        os_name = 'windows'
    else:
        os_name = 'linux'
    if browser_type == 'all':
        types = browsers.keys()
    else:
        types = [browser_type]
    total_deleted = 0
    for browser_name in types:
        if browser_name in browsers and os_name in browsers[browser_name]:
            cache_path = browsers[browser_name][os_name]
            if os.path.exists(cache_path):
                try:
                    if os_name == 'linux' and browser_name == 'firefox':
                        # Firefox 在 Linux 上使用配置文件路径
                        for profile in os.listdir(cache_path):
                            profile_cache = os.path.join(cache_path, profile, 'cache2')
                            if os.path.exists(profile_cache):
                                shutil.rmtree(profile_cache)
                                print(f"删除 {browser_name} 缓存: {profile_cache}")
                                total_deleted += 1
                    else:
                        for item in os.listdir(cache_path):
                            item_path = os.path.join(cache_path, item)
                            if os.path.isfile(item_path):
                                os.remove(item_path)
                            else:
                                shutil.rmtree(item_path)
                            total_deleted += 1
                        print(f"清空 {browser_name} 缓存目录")
                except Exception as e:
                    print(f"删除 {browser_name} 缓存失败: {e}")
            else:
                print(f"未找到 {browser_name} 缓存目录: {cache_path}")
    return total_deleted
# 使用示例
# delete_browser_cache('chrome')
# delete_browser_cache('all')

删除系统临时文件

import tempfile
import shutil
import os
from pathlib import Path
def cleanup_temp_files(days_old=7):
    """
    清理系统临时文件
    :param days_old: 删除多少天前的临时文件
    """
    import time
    now = time.time()
    cutoff = now - (days_old * 86400)  # 转换为秒
    temp_dirs = [
        tempfile.gettempdir(),
        os.path.join(os.path.expanduser("~"), "AppData", "Local", "Temp") if os.name == 'nt' else None,
        '/tmp' if os.name != 'nt' else None
    ]
    deleted_count = 0
    for temp_dir in temp_dirs:
        if temp_dir and os.path.exists(temp_dir):
            try:
                for root, dirs, files in os.walk(temp_dir, topdown=False):
                    # 删除过期文件
                    for file in files:
                        file_path = os.path.join(root, file)
                        try:
                            if os.path.getmtime(file_path) < cutoff:
                                os.remove(file_path)
                                deleted_count += 1
                        except:
                            pass
                    # 删除空目录
                    for dir in dirs:
                        dir_path = os.path.join(root, dir)
                        try:
                            if not os.listdir(dir_path):
                                os.rmdir(dir_path)
                                deleted_count += 1
                        except:
                            pass
            except Exception as e:
                print(f"清理临时目录 {temp_dir} 时出错: {e}")
    return deleted_count
# 使用示例
# cleanup_temp_files(days_old=3)

删除Python项目中的缓存

import os
import shutil
from pathlib import Path
def clean_python_project_cache(project_path="."):
    """
    清理Python项目中的缓存文件
    """
    patterns = [
        '__pycache__',
        '*.pyc',
        '*.pyo',
        '.pytest_cache',
        '.mypy_cache',
        '.cache',
        '*.egg-info',
        '*.egg',
        'dist',
        'build',
        '.tox',
        '.coverage',
        'htmlcov',
        '.eggs'
    ]
    deleted_count = 0
    project_dir = Path(project_path)
    for pattern in patterns:
        if '*' in pattern:
            # 文件模式
            for file_path in project_dir.rglob(pattern):
                try:
                    file_path.unlink()
                    print(f"删除缓存文件: {file_path}")
                    deleted_count += 1
                except Exception as e:
                    print(f"删除失败 {file_path}: {e}")
        else:
            # 目录模式
            for dir_path in project_dir.rglob(pattern):
                try:
                    if dir_path.is_dir():
                        shutil.rmtree(dir_path)
                        print(f"删除缓存目录: {dir_path}")
                        deleted_count += 1
                except Exception as e:
                    print(f"删除失败 {dir_path}: {e}")
    print(f"共清理 {deleted_count} 个Python缓存对象")
    return deleted_count
# 使用示例
# clean_python_project_cache("./my_project")

综合缓存清理工具

import os
import shutil
import tempfile
from pathlib import Path
import platform
class CacheCleaner:
    """综合缓存清理类"""
    def __init__(self, verbose=True):
        self.verbose = verbose
        self.system = platform.system().lower()
        self.home = os.path.expanduser("~")
        self.total_deleted = 0
    def log(self, message):
        """日志输出"""
        if self.verbose:
            print(message)
    def clean_python_cache(self, path="."):
        """清理Python缓存"""
        patterns = ['__pycache__', '*.pyc', '*.pyo', '.pytest_cache', '.mypy_cache']
        project_dir = Path(path)
        for pattern in patterns:
            if '*' in pattern:
                for file_path in project_dir.rglob(pattern):
                    try:
                        file_path.unlink()
                        self.total_deleted += 1
                        self.log(f"删除缓存文件: {file_path}")
                    except Exception as e:
                        self.log(f"删除失败 {file_path}: {e}")
            else:
                for dir_path in project_dir.rglob(pattern):
                    try:
                        if dir_path.is_dir():
                            shutil.rmtree(dir_path)
                            self.total_deleted += 1
                            self.log(f"删除缓存目录: {dir_path}")
                    except Exception as e:
                        self.log(f"删除失败 {dir_path}: {e}")
    def clean_browser_cache(self):
        """清理浏览器缓存"""
        browsers = {
            'chrome': {
                'windows': os.path.join(os.getenv('LOCALAPPDATA'), 'Google', 'Chrome', 'User Data', 'Default', 'Cache'),
                'darwin': os.path.join(self.home, 'Library', 'Caches', 'Google', 'Chrome'),
                'linux': os.path.join(self.home, '.cache', 'google-chrome')
            },
            'firefox': {
                'windows': os.path.join(os.getenv('APPDATA'), 'Mozilla', 'Firefox', 'Profiles'),
                'darwin': os.path.join(self.home, 'Library', 'Caches', 'Firefox'),
                'linux': os.path.join(self.home, '.cache', 'mozilla', 'firefox')
            },
            'edge': {
                'windows': os.path.join(os.getenv('LOCALAPPDATA'), 'Microsoft', 'Edge', 'User Data', 'Default', 'Cache'),
                'darwin': os.path.join(self.home, 'Library', 'Caches', 'Microsoft Edge'),
            }
        }
        for browser_name, paths in browsers.items():
            if self.system in paths:
                cache_path = paths[self.system]
                if os.path.exists(cache_path):
                    try:
                        if os.path.isdir(cache_path):
                            shutil.rmtree(cache_path)
                            self.log(f"清理 {browser_name} 缓存")
                            self.total_deleted += 1
                    except Exception as e:
                        self.log(f"清理 {browser_name} 缓存失败: {e}")
    def clean_temp_files(self):
        """清理临时文件"""
        temp_dir = tempfile.gettempdir()
        try:
            for item in os.listdir(temp_dir):
                item_path = os.path.join(temp_dir, item)
                try:
                    if os.path.isfile(item_path):
                        os.remove(item_path)
                    else:
                        shutil.rmtree(item_path)
                    self.total_deleted += 1
                except:
                    pass
            self.log(f"清理临时目录: {temp_dir}")
        except Exception as e:
            self.log(f"清理临时文件失败: {e}")
    def clean_all(self):
        """清理所有缓存"""
        self.log("开始清理缓存...")
        self.clean_python_cache()
        self.clean_browser_cache()
        self.clean_temp_files()
        self.log(f"清理完成,共删除 {self.total_deleted} 个缓存对象")
        return self.total_deleted
# 使用示例
# cleaner = CacheCleaner()
# cleaner.clean_all()

使用注意事项

  1. 权限问题:某些系统目录需要管理员权限
  2. 数据安全:删除前确保缓存不是重要数据
  3. 进程占用:被使用的缓存文件可能无法删除
  4. 定期清理:建议设定定期自动清理

这些脚本可以根据你的具体需求进行调整,如需特定场景的缓存清理,请告诉我具体需求。

抱歉,评论功能暂时关闭!