首页 > 解决方案 > 卸载包时如何在 pipenv 中自动删除依赖的 Python 包?

问题描述

当你pipenv用来安装一个包时,所有的依赖包也会被安装。卸载该软件包pipenv uninstall不会自动删除相关软件包。

如何pip-autoremove在 pipenv 中获得等效的功能?

例如:

$ cd testpipenv
$ pipenv install requests
$ pipenv shell
(testpipenv) $ pipenv graph

requests==2.24.0
 - certifi [required: >=2017.4.17, installed: 2020.6.20]
 - chardet [required: >=3.0.2,<4, installed: 3.0.4]
 - idna [required: >=2.5,<3, installed: 2.10]
 - urllib3 [required: >=1.21.1,<1.26,!=1.25.1,!=1.25.0, installed: 1.25.9]

(testpipenv) $ pipenv uninstall requests
(testpipenv) $ pip list

Package    Version
---------- ---------
certifi    2020.6.20
chardet    3.0.4
idna       2.10
pip        20.1.1
setuptools 47.3.1
urllib3    1.25.9
wheel      0.34.2

的依赖包requests,例如urllib3仍然安装,可以通过以下方式验证

(testpipenv) $ python 
>>> import urllib3

此处也对此进行了讨论:Pipenv 卸载不卸载依赖项 - 问题 #1470,我还没有找到关于使用 pipenv 自动删除软件包的最新指令集。

使用的版本:

标签: pythonpython-3.xpipuninstallationpipenv

解决方案


TL;博士

(testpipenv) $ pipenv uninstall requests && pipenv clean

为了获得与pip-autoremove仅使用pipenv命令类似的功能,我执行了以下操作,继续上面的示例:

(testpipenv) $ pipenv graph
 
certifi==2020.6.20
chardet==3.0.4
idna==2.10
urllib3==1.25.9

这表明仍然安装了依赖包,但它们已经从 Pipfile.lock 中删除。因此,使用pipenv clean将删除它们:

(testpipenv) $ pipenv clean

Uninstalling certifi…
Uninstalling idna…
Uninstalling urllib3…
Uninstalling chardet…

总之...

(testpipenv) $ pipenv uninstall requests && pipenv clean

... 将删除所有依赖包,并且最接近pip-autoremove.

这可能比预期更激进,因为clean命令“卸载所有未在 Pipfile.lock 中指定的包” 如果在使用 clean 之前未将包添加到 Pipfile.lock,则此命令可能会删除超出预期的内容。我不知道这是否真的是一个问题,因为uninstall自动更新 Pipfile.lock 除非--skip-lock指定了其他选项。


另一种选择是...

pipenv --rm && pipenv install

...这将删除所有内容并基于 Pipfile.lock 重建虚拟环境。这会起作用,但速度很慢,因为它会删除完整的虚拟环境并重新安装所有东西,除了不需要的依赖项。


推荐阅读