Python Task Package Installation and Import Guide
This guide explains how to temporarily install third-party packages at Python task runtime and import them in subsequent code.
Applicable Scenarios
- Need to temporarily install third-party packages at task runtime.
- Need to install packages from PyPI or a package mirror such as the Tsinghua mirror.
- Need to install packages to a temporary directory under
/tmpbeforeimport.
Runtime Installation Notes
- Python tasks run in temporary Pods, and the environment is destroyed after the task completes. Dependencies must be reinstalled on every run; do not rely on a previous installation.
- Python tasks run as a non-root user and cannot install dependencies into the system-level
site-packagesdirectory. Use--targetto install packages into a dedicated temporary directory under/tmp, and add that directory tosys.pathbefore importing. /tmpis available only for temporary files during the current task run. Do not use it for data that must persist after the task completes.
Standard Template (Recommended for Direct Reuse)
Quick Switch to Tsinghua Mirror
If access to PyPI is slow, change INDEX_URL in the template to the Tsinghua mirror:
Common Errors and Troubleshooting
Error: ModuleNotFoundError: No module named 'xxx'
Check in order:
- Whether
--targetwas used but that directory was not added tosys.path. - Whether the directory was added to
sys.pathonly after theimportstatement. - Whether
sys.path.append()added the path at the end, allowing another module with the same name to shadow the installed package. Usesys.path.insert(0, TARGET_DIR)instead. - Whether the package name and module name match (some packages are
pip install A, butimport B).
Error: Permission denied
Check whether --target points to a directory under /tmp. Do not use /home, the system site-packages directory, or any other directory that is not explicitly documented as writable.
