Files

43 lines
1.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
sources: [summaries/02_Third_party.md]
brief: site-packages 是 Python 环境中存放第三方包的典型目录,直接影响 import 能否找到已安装包。
---
# site-packages
## 概念定义
`site-packages` 是 Python 环境中存放第三方包的典型目录。通过 `pip` 安装的包通常会进入当前 Python 环境对应的 `site-packages`,然后由 `import` 机制在搜索路径中找到。
这个主题连接 [[concepts/pip-与-PyPI]]、[[concepts/模块与-import]]、[[concepts/包与虚拟环境]] 和 [[concepts/依赖管理]]。
## 为什么它重要
“已经安装了包”不等于“当前程序能导入包”。更准确的问题是:包是否安装到了当前正在运行的 Python 解释器会搜索的 `site-packages` 中?
```python
import numpy
print(numpy)
```
查看模块对象可以帮助确认实际加载位置。
## 多环境问题
系统 Python、用户安装目录和各个虚拟环境都可能有不同的 `site-packages`。如果 `python`、`pip` 或虚拟环境没有对齐,就会出现安装成功但导入失败的问题。
## 排查顺序
- 确认当前运行的是哪个 `python`;
- 使用 `python -m pip` 而不是不确定来源的 `pip`;
- 查看模块对象的 `__file__` 或打印模块对象;
- 检查虚拟环境是否已激活;
- 检查 `sys.path` 是否包含预期目录。
## 相关概念
- [[concepts/pip-与-PyPI]]
- [[concepts/模块与-import]]
- [[concepts/包与虚拟环境]]
- [[concepts/依赖管理]]