如何缓存下载的PIP软件包

64

如何防止PIP重新下载已经下载的软件包?我正在安装一个11MB的matplotlib软件包,它依赖于几个特定于发行版的软件包。每次运行pip install matplotlib时,它都会重新下载matplotlib。我该如何停止这个过程?

3个回答

114

注意: 只有通过HTTPS下载的包才会被缓存。如果你使用的是自定义库并通过普通的HTTP下载,缓存将被禁用

对于新版本的Pip:

新版本的Pip默认现在缓存下载内容。请查阅此文档:

https://pip.pypa.io/en/stable/topics/caching/

对于旧版本的Pip:

创建一个名为~/.pip/pip.conf的配置文件,并添加以下内容:

[global]
download_cache = ~/.cache/pip

一条命令搞定:

printf '[global]\ndownload_cache = ~/.cache/pip\n' >> ~/.pip/pip.conf

1
酷,简单,并且不需要记住每次添加参数。我浪费了很多GB重新下载东西。谢谢你。 - m3nda
谢谢,如果您使用pip3下载要求并获得黄色文本警告,则可以mkdir ~/.cache/pip,然后警告将消失。 - 水清木华
我已经添加了一条注释,建议使用HTTPS。在pip 21.3(2021-10-11)中,有一个名为“--trusted-host”选项可以启用特定域上的HTTP缓存。 - user5994461
顺便问一下,pip缓存中的软件包生命周期(TTL)是多久? - Muhammad Faizan-Ul-Haq

64

您可以使用特定的环境变量PIP_DOWNLOAD_CACHE,将其指向一个存储包的目录。如果它们需要再次安装,则将从此目录中获取。

似乎还有一个额外的选项 pip --download-cache 可以做类似的事情,但我自己从未尝试过。对于您的示例,为了避免每次重新下载matplotlib,您可以执行以下操作:

pip install --download-cache /path/to/pip/cache matplotlib

那是否解答了您的问题?


我不确定PIP是否也这样做,但是如果你在本地目录中有一个.tar(或者可能是zip?)文件作为包,使用easy_install将首先尝试使用该文件。 - Wayne Werner
2
也要看看pip-accel。它是解决这个问题的一个新而更好的方案。 - qris
11
自pip 8版本起,"--download-cache"选项已被删除。pip默认应该使用缓存,可以通过"--no-cache-dir"选项关闭缓存。 - Ski
我在https://pip.pypa.io/en/stable/topics/caching/中没有看到PIP_DOWNLOAD_CACHE的提及,但我猜这可能是我们了解通用pip环境变量的地方:https://pip.pypa.io/en/stable/topics/configuration/#environment-variables - rfay
RIP pip-accel :(((( - jtlz2

8

您可以

# download and extract package to build path
pip install --no-install matplotlib

# the build path could be found by 
pip install --help|grep Unpack\ packages\ into -A 2

# then rm pip-delete-this-directory.txt inside the build path
# this prevent pip from removing package from the build directory after install
# you could check the content of the file
rm build/pip-delete-this-directory.txt

# from now on you could install matplotlib quickly
# this uses single build directory 
# and can speed up compiling by caching intermediate objects.
pip install --no-download matplotlib

此外,您可以手动下载该软件包。
pip install -d dir_for_packages matplotlib

然后通过解压和python setup install安装它。

pip install --download-cache的工作方式类似,但有额外的检查:首先从网络上搜索目标软件包的最新版本或指定版本,如果搜索结果并且缓存目录中存在缓存软件包,则使用缓存软件包而不是下载。例如,

pip install --download-cache . pymongo

将下载pymongo包到当前目录:

http%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2Fp%2Fpymongo%2Fpymongo-2.1.1.tar.gz
http%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2Fp%2Fpymongo%2Fpymongo-2.1.1.tar.gz.content-type

1
这些选项虽然有用,但自pip 7以后不再受支持。 - eddie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接