本文目录导读:

- 清空Python内存缓存(如lru_cache、functools.cache)
- 清空requests库的缓存
- 清空文件系统缓存(如pickle、json文件)
- 清空字典/对象缓存
- 清空数据库缓存(如SQLite)
- 清空Redis缓存
- 通用缓存清理函数
- 注意事项
在Python中清空本地缓存数据需要根据不同的缓存类型采用不同的方法,以下是几种常见情况的解决方案:
清空Python内存缓存(如lru_cache、functools.cache)
from functools import lru_cache
@lru_cache(maxsize=None)
def cached_function(x):
return x * 2
# 清空特定函数的缓存
cached_function.cache_clear()
# 清空所有函数缓存(需要手动调用每个函数)
# 或者使用装饰器模式统一管理
清空requests库的缓存
import requests # 清空requests会话缓存 session = requests.Session() session.cookies.clear() # 清理连接池 requests.adapters.HTTPAdapter().close() requests.sessions.Session().close()
清空文件系统缓存(如pickle、json文件)
import os
import shutil
# 清空特定缓存目录
cache_dir = "cache"
if os.path.exists(cache_dir):
shutil.rmtree(cache_dir)
os.makedirs(cache_dir) # 重建空目录
清空字典/对象缓存
class CacheManager:
def __init__(self):
self._cache = {}
def clear(self):
"""清空所有缓存"""
self._cache.clear()
# 使用示例
cache_manager = CacheManager()
cache_manager.clear()
清空数据库缓存(如SQLite)
import sqlite3
def clear_sqlite_cache(db_path):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 清空缓存表
cursor.execute("DELETE FROM cache_table")
conn.commit()
# 执行VACUUM以释放空间
conn.execute("VACUUM")
conn.close()
清空Redis缓存
import redis
def clear_redis_cache():
r = redis.Redis(host='localhost', port=6379, db=0)
# 清空所有键
r.flushdb()
# 或清空特定模式的键
keys = r.keys("cache:*")
if keys:
r.delete(*keys)
通用缓存清理函数
import os
import shutil
import tempfile
import sys
def clear_all_cache():
"""清空所有已知的缓存位置"""
# 1. 清空系统临时目录中的Python相关缓存
temp_dir = tempfile.gettempdir()
for root, dirs, files in os.walk(temp_dir):
for file in files:
if file.endswith('.pyc') or file.startswith('.cache'):
try:
os.remove(os.path.join(root, file))
except:
pass
# 2. 清空__pycache__目录
for root, dirs, files in os.walk('.'):
if '__pycache__' in dirs:
pycache_path = os.path.join(root, '__pycache__')
try:
shutil.rmtree(pycache_path)
print(f"已清空: {pycache_path}")
except Exception as e:
print(f"清空失败: {e}")
# 3. 清空常见的缓存目录
cache_dirs = [
'.cache',
'cache',
'__pycache__',
'.pytest_cache',
'.mypy_cache',
]
for cache_dir in cache_dirs:
if os.path.exists(cache_dir) and os.path.isdir(cache_dir):
try:
shutil.rmtree(cache_dir)
print(f"已清空缓存目录: {cache_dir}")
except Exception as e:
print(f"清空失败 {cache_dir}: {e}")
# 使用示例
if __name__ == "__main__":
clear_all_cache()
注意事项
- 谨慎操作:清空缓存可能导致数据丢失或程序性能下降
- 指定范围:最好只清空你知道来源的缓存
- 备份重要数据:在执行清空操作前确保重要数据已备份
- 权限问题:某些系统缓存目录可能需要管理员权限
根据你的具体需求选择合适的清空方法,如果你能提供更具体的缓存类型(如某个特定库的缓存),我可以给出更精确的解决方案。