How can I safely check if a python package is outdated?

3.8k views Asked by At

I want to include some kind of self-update mechanism on a python package and I do not want to call pip update before the script is run as it is very slow, I am looking for a smart mechanism.

Every time it is used it could make an HTTP call, probably to PyPi and if it would detect a new version it would output a warning on STDERR.

Obviously, as part of this process I would also want to cache the result of last call, so the library would not check for updates more than once a day, let say.

Does anyone has something like this already implemented? Do you have an example that can be used to cache results from HTTP calls, between different executions, so it would not impose signifiant delays?

2

There are 2 answers

0
Alex Hall On BEST ANSWER

I've written a library outdated to solve this problem. The quickest way to use it is to insert code like this somewhere at the root of your package:

from outdated import warn_if_outdated

warn_if_outdated('my-package-name', '1.2.3')

This will output a warning on stderr as requested, cache the HTTP call for 24 hours, and more. Details can be found in the link above.

It's also much faster than pip list -o even without caching.

6
Wolph On

To show the outdated packages you can simply run pip list -o, but that doesn't involve any caching by itself.

Although it would be trivial to simply add pip list -o > outdated.txt to a cronjob so it automatically updates daily :)

Here's some example code to use pip as a library:

def get_outdated():
    import pip

    list_command = pip.commands.list.ListCommand()
    options, args = list_command.parse_args([])
    packages = pip.utils.get_installed_distributions()

    return list_command.get_outdated(packages, options)

print(get_outdated())