我正在尝试修复我的一个virtualenv -我想将所有已安装的库重置为与生产相匹配的库。

有没有一种快速简单的方法来处理皮普?


当前回答

这是我卸载所有python包的最简单的方法。

from pip import get_installed_distributions
from os import system
for i in get_installed_distributions():
    system("pip3 uninstall {} -y -q".format(i.key))

其他回答

使用pip list或pip freeze的其他答案必须包括——local,否则它还将卸载在公共名称空间中找到的包。

下面是我经常使用的代码片段

 pip freeze --local | xargs pip uninstall -y

参考:pip freeze——救命

我使用——user选项卸载安装在用户站点上的所有包。

pip3 freeze --user | xargs pip3 uninstall -y

这是我卸载所有python包的最简单的方法。

from pip import get_installed_distributions
from os import system
for i in get_installed_distributions():
    system("pip3 uninstall {} -y -q".format(i.key))

我想把这个答案从评论区提升出来,因为它是线程中最优雅的解决方案之一。这个答案完全归功于@joeb。

pip uninstall -y -r <(pip freeze)

这对于我在virtualenv上下文之外清除我的用户包文件夹的用例非常有用,上面的许多答案都不能处理。

编辑:有人知道如何使这个命令在Makefile中工作吗?

额外好处:bash别名

为了方便起见,我把这个添加到我的bash配置文件中:

alias pipuninstallall="pip uninstall -y -r <(pip freeze)"

然后运行:

pipuninstallall

Pipenv的替代方案

如果你正在使用pipenv,你可以运行:

pipenv uninstall --all

诗歌的替代品

如果你正在使用诗歌,运行:

poetry env remove --python3.9

(请注意,您需要更改那里的版本号,以匹配您的Python版本。)

我找到了这个片段作为替代解决方案。这是一个比重做virtualenv更优雅的删除库:

pip freeze | xargs pip uninstall -y

如果你有通过VCS安装的包,你需要排除这些行并手动删除包(从下面的注释中提升):

pip freeze | grep -v "^-e" | xargs pip uninstall -y

如果你有直接从github/gitlab安装的包,这些包将有@。 如:

django @ git+https://github.com/django.git@<sha>

您可以添加cut -d "@" -f1来获得卸载所需的包名。

pip freeze | cut -d "@" -f1 | xargs pip uninstall -y