---
title: "关于Python的 __pycache__ 文件夹小记"
url: "https://versun.me/python-pycache-notes"
markdown_url: "https://versun.me/python-pycache-notes.md"
format: "note"
published: "2024-05-14T08:19:21.000Z"
updated: "2026-01-05T05:30:18.000Z"
collections:
  - "Blog"
site: "Versun"
---

# 关于Python的 __pycache__ 文件夹小记

ref: [https://realpython.com/python-pycache/#what-actions-invalidate-the-cache](https://realpython.com/python-pycache/#what-actions-invalidate-the-cache)

- Python 中的 `__pycache__` 文件夹是什么？  
Python模块的缓存文件夹，将需要的模块编译为字节码，并缓存(.pyc)到该文件夹中，实现更快的导入速度。  
除了`__pycache__` 文件夹，Python还在内存中创建了模块缓存，缓存需要导入多次的模块，减少导入模块的开销。
- 如何判断缓存的模块是否过期？  
默认基于时间戳判断，也可以基于哈希值
- 即使使用了 from … import 语法，Python 还是会读取并编译整个模块，包括未使用的。
- 可以在python命令后使用-X importtime参数来显示每个模块的导入时间
- 递归删除所有 `__pycache__` 文件夹(linux)：`find . -type d -name __pycache__ -exec rm -rf {} +`
- 如何禁止Python创建缓存文件？  
向 python 命令传递 -B 选项，或者设置环境变量`PYTHONDONTWRITEBYTECODE=1`
- 集中存储缓存  
方法1：`python -X pycache_prefix=/tmp/pycache calculator.py`  
方法2：设置环境变量`PYTHONPYCACHEPREFIX=/tmp/pycache`  
它会在指定的文件夹下镜像项目的目录结构，由于这种集中式缓存的层次结构与项目结构相匹配，因此可以在多个项目之间共享该缓存文件夹
