python
module_error
ai_generated
true
ImportError:pip install --target ./lib requests 后找不到名为 'requests' 的模块
ImportError: No module named 'requests' after pip install --target ./lib requests
ID: python/pip-target-not-in-path
80%修复率
88%置信度
0证据数
2024-05-30首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
pip install --target 将包安装到指定目录,但不会将其添加到 sys.path。除非更新 PYTHONPATH 或 sys.path,否则解释器找不到该包。
English
pip install --target installs into the given directory but does not add it to sys.path. The interpreter cannot find the package unless PYTHONPATH or sys.path is updated.
解决方案
-
95% 成功率
export PYTHONPATH=$PWD/lib:$PYTHONPATH && python -c 'import requests'
-
90% 成功率
import sys, os; sys.path.insert(0, os.path.abspath('./lib')); import requests -
85% 成功率
echo $(pwd)/lib > $(python -c 'import site; print(site.getsitepackages()[0])')/mylib.pth
无效尝试
常见但无效的做法:
-
95% 失败
Reinstalling does not change sys.path.
-
90% 失败
pip still installs to the active environment's site-packages, not the cwd.