0

I have a simple CLI made with Python. Each time it's run, I want to check if it is updated to the latest version and print a little message if it isn't.

I believe that this bit of code

import pkg_resources
installed_version = pkg_resources.get_distribution("videocloud").version

should tell me which version is installed, but I can't find a way to tell what the latest version is.

Is there some sort of API that can get the latest version of a PyPI module?

Param
  • 609
  • 2
  • 5
  • 16
  • https://stackoverflow.com/questions/4888027/python-and-pip-list-all-versions-of-a-package-thats-available Does this help? – ComplicatedPhenomenon Jul 16 '19 at 22:19
  • More precisely: https://stackoverflow.com/a/40745656/5218354 – norok2 Jul 16 '19 at 22:28
  • 1
    Possible duplicate of [Python and pip, list all versions of a package that's available?](https://stackoverflow.com/questions/4888027/python-and-pip-list-all-versions-of-a-package-thats-available) – norok2 Jul 16 '19 at 22:29
  • `subprocess.getoutput('pip list').splitlines()` will return a list of entry's like `numpy (version)` – Legorooj Jul 17 '19 at 08:02
  • @Legorooj that seems to show the installed version, which I already have with `pkg_resources.get_distribution("videocloud").version`. What I'm looking for is the latest version – Param Jul 17 '19 at 13:32
  • Ah sorry I thought you had neither for some weird reason. Will look at this... – Legorooj Jul 17 '19 at 15:45

1 Answers1

1

I wrote this script using beautifulsoup4 and urllib - so you'll need an internet connection for it to run.

import bs4 as bs
import urllib.request as request

repo = input('Please enter a repository name: ')

soup = bs.BeautifulSoup(request.urlopen(f'https://pypi.org/project/{repo}/'), 'lxml')

title = []
for item in soup.find_all('h1', {'class': 'package-header__name'}):
    title.append(item.text)

version = title[0].split()[-1]

print(version)

This works because the title on the pypi website has the version in it, and has a html identifier that allows you to find the title easily. EG:

pypi website

Sample run:

Please enter a repository name: pyaes
1.6.1

Also as a function:

def version(repo):
    try:
        soup = bs.BeautifulSoup(request.urlopen(f'https://pypi.org/project/{repo}/'), 'lxml')

        title = []
        for item in soup.find_all('h1', {'class': 'package-header__name'}):
            title.append(item.text)

        return title[0].split()[-1]
    except urllib.error.URLError as e:
        print('No internet connection')
Legorooj
  • 2,646
  • 2
  • 15
  • 35
  • 1
    How about parsing [simple index](https://pypi.org/simple/cryptography/) instead of the complicated website that might change its layout? Also see [PEP 503](https://www.python.org/dev/peps/pep-0503/) – asikorski Jul 19 '19 at 12:49
  • Hmm. I shall look into this for future answers. Thanks though! – Legorooj Jul 20 '19 at 08:36