Phyton How to check if python package is latest version programmatically? python check python package version

How do you check if a package is at its latest version programmatically in a script and return a true or false?

I can check with a script like this:

package='gekko'
import pip
if hasattr(pip, 'main'):
    from pip import main as pipmain
else:
    from pip._internal import main as pipmain
pipmain(['search','gekko'])

or with command line:

(base) C:\User>pip search gekko
gekko (0.2.3)  - Machine learning and optimization for dynamic systems
  INSTALLED: 0.2.3 (latest)

But how do I check programmatically and return true or false?

Answer:1

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

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
Answer:2

Edit: Remove pip search

Thanks for the several suggestions. Here is a new version that doesn't use pip search but instead pulls the latest version directly from pypi as proposed by Daniel Hill. This also resolves the issue with the substring false matches.

def check(name):
    import subprocess
    import sys
    import json
    import urllib.request

    # create dictionary of package versions
    pkgs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
    keys = [p.decode().split('==')[0] for p in pkgs.split()]
    values = [p.decode().split('==')[1] for p in pkgs.split()]
    d = dict(zip(keys, values)) # dictionary of all package versions

    # retrieve info on latest version
    contents = urllib.request.urlopen('https://pypi.org/pypi/'+name+'/json').read()
    data = json.loads(contents)
    latest_version = data['info']['version']

    if d[name]==latest_version:
        print('Latest version (' + d[name] + ') of '+str(name)+' is installed')
        return True
    else:
        print('Version ' + d[name] + ' of '+str(name)+' not the latest '+latest_version)
        return False

print(check('gekko'))

Original Response

Here is a fast solution that retrieves latest version information on only the gekko package of interest.

def check(name):
    import subprocess
    import sys
    # create dictionary of package versions
    pkgs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
    keys = [p.decode().split('==')[0] for p in pkgs.split()]
    values = [p.decode().split('==')[1] for p in pkgs.split()]
    d = dict(zip(keys, values)) # dictionary of all package versions

    # retrieve info on latest version
    s = subprocess.check_output([sys.executable, '-m', 'pip', 'search', name])

    if d[name] in s.decode():  # weakness
        print('Latest version (' + d[name] + ') of '+str(name)+' is installed')
        return True
    else:
        print(s.decode())
        return False

print(check('gekko'))

This produces the message Latest version (0.2.3) of gekko is installed and returns True to indicate latest version (or False if not the latest version). This may not be the best solution because it only checks for a version substring with if d[name] in s.decode(): but it is faster than pip list --outdated that checks all the packages. This isn't the most reliable method because it will return an incorrect True if current installed version is 0.2.3 but latest version is 0.2.30 or 0.2.3a. An improvement would be to programmatically get the latest version and do a direct comparison.

Answer:3

Latest version:

My project luddite has this feature:

>>> import luddite
>>> luddite.get_version_pypi("gekko")
'0.2.3'

Installed version:

The canonical way to check installed version is just to access the __version__ attribute of the top-level namespace:

>>> import gekko
>>> gekko.__version__
'0.2.0'

Unfortunately not all projects set this attribute. When they don't, you can use pkg_resources to dig it out from the metadata:

>>> import pkg_resources
>>> pkg_resources.get_distribution("gekko").version
'0.2.0'
Answer:4



  1. python check python package version

I have code that hides parts of the pdf (by just covering it with a white polygon) but the issue with this is, the text is still there, if you ctrl-f you can still find it. My goal is to actually ...

I have code that hides parts of the pdf (by just covering it with a white polygon) but the issue with this is, the text is still there, if you ctrl-f you can still find it. My goal is to actually ...

I have a model that I've trained for 40 epochs. I kept checkpoints for each epochs, also saved the model with model.save(). The code for training is n_units = 1000 model = Sequential() model.add(LSTM(...

I have a model that I've trained for 40 epochs. I kept checkpoints for each epochs, also saved the model with model.save(). The code for training is n_units = 1000 model = Sequential() model.add(LSTM(...