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

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


当前回答

这是对我有用的命令:

pip list | awk '{print $1}' | xargs pip uninstall -y

其他回答

pip3 freeze --local | xargs pip3 uninstall -y

情况可能是必须多次运行此命令才能获得空pip3 freeze—local。

仅使用pip的跨平台支持:

#!/usr/bin/env python

from sys import stderr
from pip.commands.uninstall import UninstallCommand
from pip import get_installed_distributions

pip_uninstall = UninstallCommand()
options, args = pip_uninstall.parse_args([
    package.project_name
    for package in
    get_installed_distributions()
    if not package.location.endswith('dist-packages')
])

options.yes = True  # Don't confirm before uninstall
# set `options.require_venv` to True for virtualenv restriction

try:
    print pip_uninstall.run(options, args)
except OSError as e:
    if e.errno != 13:
        raise e
    print >> stderr, "You lack permissions to uninstall this package.
                      Perhaps run with sudo? Exiting."
    exit(13)
# Plenty of other exceptions can be thrown, e.g.: `InstallationError`
# handle them if you want to.

(添加这个作为答案,因为我没有足够的声誉来评论@blueberryfields的回答)

@blueberryfields的答案工作得很好,但如果没有包可以卸载(如果这个“卸载全部”是脚本或makefile的一部分,这可能是一个问题)。当使用GNU版本的xargs时,这个问题可以用xargs -r来解决:

pip freeze --exclude-editable | xargs -r pip uninstall -y

来自man xargs:

- r, no-run-if-empty 如果标准输入中不包含非空字符,请不要执行该命令。通常情况下,该命令即使存在也只运行一次 没有输入。这个选项是一个GNU扩展。

在Windows上,如果你的路径配置正确,你可以使用:

pip freeze > unins && pip uninstall -y -r unins && del unins

对于类unix系统应该是类似的情况:

pip freeze > unins && pip uninstall -y -r unins && rm unins

只是一个警告,这不是完全可靠的,因为你可能会遇到诸如“文件未找到”等问题,但它可能在某些情况下仍然有效

编辑:为清晰起见:unins是一个任意文件,当该命令执行时,该文件中写入了数据

然后,它编写的文件被用于通过pip uninstall -y -r unins在隐含同意/事先批准的情况下卸载上述软件包

文件最终在完成时被删除。

这是我卸载所有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))