在 Python 里,若要快速下载依赖,可采用以下几种方法:
Python 依赖通常从 Python Package Index(PyPI)下载,不过由于网络问题,从国外源下载速度可能较慢。你可以使用国内的镜像源来加快下载速度,国内常见的镜像源有阿里云、豆瓣、清华大学等。
使用 pip
命令时,通过 -i
参数指定镜像源,示例如下:
pip install package_name -i https://mirrors.aliyun.com/pypi/simple/
上述命令使用阿里云镜像源下载 package_name
包。你还能使用其他镜像源,例如:
https://pypi.doubanio.com/simple/
https://pypi.tuna.tsinghua.edu.cn/simple
你可以修改 pip
的配置文件,让后续所有的 pip
操作都使用指定的镜像源。
在 Windows 系统下,在 %APPDATA%\pip\
目录(通常是 C:\Users\你的用户名\AppData\Roaming\pip
)创建 pip.ini
文件,文件内容如下:
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
在 Linux 或 macOS 系统下,在 ~/.pip/
目录创建 pip.conf
文件,内容同样为:
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
pip
的并发下载功能pip
从 20.3 版本开始支持并发下载依赖,你可以通过 --use-feature=fast-deps
参数开启此功能,示例如下:
pip install package_name --use-feature=fast-deps
此功能会并行下载多个依赖包,从而加快下载速度。
pipreqs
批量下载项目依赖若要下载整个项目的依赖,可以使用 pipreqs
工具自动生成项目的依赖文件 requirements.txt
,再一次性下载所有依赖。
pipreqs
pip install pipreqs
requirements.txt
文件在项目根目录下执行以下命令:
pipreqs .
该命令会自动扫描项目文件,生成 requirements.txt
文件,其中包含项目所需的所有依赖及其版本。
在项目根目录下执行以下命令,一次性下载 requirements.txt
中的所有依赖:
pip install -r requirements.txt
conda
管理依赖(针对 Anaconda 或 Miniconda 用户)如果你使用 Anaconda 或 Miniconda 环境,可以使用 conda
命令来管理依赖。conda
有自己的镜像源,且在某些情况下下载速度更快。
conda
镜像源可以使用以下命令配置清华大学的 conda
镜像源:
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --set show_channel_urls yes
使用 conda
安装依赖的命令如下:
conda install package_name
通过上述方法,你能够显著提升 Python 依赖的下载速度。