How to check if python package is latest version programmatically?

Fast Version (Checking the package only)

The code below calls the package with an unavailable version like pip install package_name==random. The call returns all the available versions. The program reads the latest version.

The program then runs pip show package_name and gets the current version of the package.

If it finds a match, it returns True, otherwise False.

This is a reliable option given that it stands on pip

import subprocess
import sys
def check(name):
    latest_version = str(subprocess.run([sys.executable, '-m', 'pip', 'install', '{}==random'.format(name)], capture_output=True, text=True))
    latest_version = latest_version[latest_version.find('(from versions:')+15:]
    latest_version = latest_version[:latest_version.find(')')]
    latest_version = latest_version.replace(' ','').split(',')[-1]

    current_version = str(subprocess.run([sys.executable, '-m', 'pip', 'show', '{}'.format(name)], capture_output=True, text=True))
    current_version = current_version[current_version.find('Version:')+8:]
    current_version = current_version[:current_version.find('\\n')].replace(' ','') 

    if latest_version == current_version:
        return True
    else:
        return False

Edit 2021: The code below no longer works with the new version of pip

The following code calls for pip list --outdated:

import subprocess
import sys

def check(name):
    reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'list','--outdated'])
    outdated_packages = [r.decode().split('==')[0] for r in reqs.split()]
    return name in outdated_packages

My project johnnydep has this feature.

In shell:

pip install --upgrade pip johnnydep
pip install gekko==0.2.0

In Python:

>>> from johnnydep.lib import JohnnyDist
>>> dist = JohnnyDist("gekko")
>>> dist.version_installed  
'0.2.0'
>>> dist.version_latest 
'0.2.3'

Tags:

Python

Pip

Gekko