Upgrading all packages with pip

2019-01-02 19:07发布

Is it possible to upgrade all Python packages at one time with pip?

Note that there is a feature request for this on the official issue tracker.

标签: python pip
30条回答
萌妹纸的霸气范
2楼-- · 2019-01-02 19:23
import pip
pkgs = [p.key for p in pip.get_installed_distributions()]
for pkg in pkgs:
    pip.main(['install', '--upgrade', pkg])

or even:

import pip
commands = ['install', '--upgrade']
pkgs = commands.extend([p.key for p in pip.get_installed_distributions()])
pip.main(commands)

Works fast as it is not constantly launching a shell. I would love to find the time to get this actually using the list outdated to speed things up still more.

查看更多
春风洒进眼中
3楼-- · 2019-01-02 19:25

The shortest and easiest on Windows.

pip freeze > requirements.txt && pip install --upgrade -r requirements.txt && rm requirements.txt
查看更多
永恒的永恒
4楼-- · 2019-01-02 19:26

@Ramana's answer worked the best for me, of those here, but I had to add a few catches:

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

The site-packages check excludes my development packages, because they are not located in the system site-packages directory. The try-except simply skips packages that have been removed from PyPI.

@endolith: I was hoping for an easy pip.install(dist.key, upgrade=True), too, but it doesn't look like pip was meant to be used by anything but the command line (the docs don't mention the internal API, and the pip developers didn't use docstrings).

查看更多
几人难应
5楼-- · 2019-01-02 19:28

This seems more concise.

pip list --outdated | cut -d ' ' -f1 | xargs -n1 pip install -U

Explanation:

pip list --outdated gets lines like these

urllib3 (1.7.1) - Latest: 1.15.1 [wheel]
wheel (0.24.0) - Latest: 0.29.0 [wheel]

In cut -d ' ' -f1, -d ' ' sets "space" as the delimiter, -f1 means to get the first column.

So the above lines becomes:

urllib3
wheel

then pass them to xargs to run the command, pip install -U, with each line as appending arguments

-n1 limits the number of arguments passed to each command pip install -U to be 1

查看更多
长期被迫恋爱
6楼-- · 2019-01-02 19:28

when using a virtualenv and if you just want to upgrade packages added to your virtualenv, you may want to do:

pip install `pip freeze -l | cut --fields=1 -d = -` --upgrade
查看更多
只若初见
7楼-- · 2019-01-02 19:29

One-liner version of @Ramana's answer.

python -c 'import pip, subprocess; [subprocess.call("pip install -U " + d.project_name, shell=1) for d in pip.get_installed_distributions()]'

`

查看更多
登录 后发表回答