#!/usr/bin/env python
import re
try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen

urldir = u"https://www.python.org/ftp/python/"

dlpage = urlopen(urldir).read().decode("utf-8")
versions = re.findall(u'''['"](3\\.[0-9][0-9.]*[0-9])/['"]''', dlpage)

versions.sort(key=lambda v: [int(n) for n in v.split(u".")])

for version in reversed(versions):
    dlpage = urlopen(urldir + version).read().decode("utf-8")
    regex = (
        u'''['"]''' +
        re.escape("Python-{version}.tar.xz".format(version=version)) +
        u'''['"]'''
    )
    if re.search(regex, dlpage):
        break
else:
    raise RuntimeError("No available Python version found.")

url = urldir + "{version}/Python-{version}.tar.xz".format(version=version)

print(url)
