python module_error ai_generated true

ImportError: No module named 'requests' after pip install --target ./lib requests

ID: python/pip-target-not-in-path

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-05-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —
3.9 active — — —
3.10 active — — —
3.11 active — — —
3.12 active — — —

Root Cause

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.

generic

中文

pip install --target 将包安装到指定目录,但不会将其添加到 sys.path。除非更新 PYTHONPATH 或 sys.path,否则解释器找不到该包。

Workarounds

  1. 95% success
    export PYTHONPATH=$PWD/lib:$PYTHONPATH && python -c 'import requests'
  2. 90% success
    import sys, os; sys.path.insert(0, os.path.abspath('./lib')); import requests
  3. 85% success
    echo $(pwd)/lib > $(python -c 'import site; print(site.getsitepackages()[0])')/mylib.pth

Dead Ends

Common approaches that don't work:

  1. 95% fail

    Reinstalling does not change sys.path.

  2. 90% fail

    pip still installs to the active environment's site-packages, not the cwd.