是否可以使用pip一次性升级所有Python包?

注意:官方问题跟踪器上对此有一个功能请求。


当前回答

我在pip问题讨论中找到的最简单、最快的解决方案是:

pip install pipdate
pipdate

资料来源:https://github.com/pypa/pip/issues/3819

其他回答

通过拉取请求发送给pip人员;同时使用我写的这个pip库解决方案:

from pip import get_installed_distributions
from pip.commands import install

install_cmd = install.InstallCommand()

options, args = install_cmd.parse_args([package.project_name
                                        for package in
                                        get_installed_distributions()])

options.upgrade = True
install_cmd.run(options, args)  # Chuck this in a try/except and print as wanted

在Windows或Linux上更新Python包

1-将已安装软件包的列表输出到需求文件(requirements.txt)中:

pip freeze > requirements.txt

2-编辑requirements.txt,并将所有“==”替换为“>=”。在编辑器中使用“全部替换”命令。

3-升级所有过时的软件包

pip install -r requirements.txt --upgrade

资料来源:https://www.activestate.com/resources/quick-reads/how-to-update-all-python-packages/

拉玛纳的回答对我来说是最好的,但我不得不补充几点:

import pip
for dist in pip.get_installed_distributions():
    if 'site-packages' in dist.location:
        try:
            pip.call_subprocess(['pip', 'install', '-U', dist.key])
        except Exception, exc:
            print exc

站点包检查排除了我的开发包,因为它们不在系统站点包目录中。try-except只是跳过已从PyPI中删除的包。

对于endolith:我也希望有一个简单的pip.install(dist.key,upgrade=True),但它看起来不像是要让命令行以外的任何东西使用pip(文档没有提到内部API,pip开发人员也没有使用docstring)。

改用pipx:

pipx upgrade-all

在我看来,这个选项更简单易懂:

pip install -U `pip list --outdated | awk 'NR>2 {print $1}'`

解释是,pip-list——过时输出所有过时包的列表,格式如下:

Package   Version Latest Type 
--------- ------- ------ -----
fonttools 3.31.0  3.32.0 wheel
urllib3   1.24    1.24.1 wheel
requests  2.20.0  2.20.1 wheel

在awk命令中,NR>2跳过前两条记录(行),{print$1}选择每行的第一个单词(正如SergioAraujo所建议的,我删除了tail-n+3,因为awk确实可以处理跳过记录)。