1# This file must use Python 1.5 syntax.
2import sys, string, os, glob, re
3
4
5class base_check_python_version:
6    def __init__(self):
7        version = None
8        try:
9            version = sys.version_info[0:2]
10        except AttributeError:
11            pass # pre 2.0, no neat way to get the exact number
12
13        # The change to prefer 2.4 really messes up any systems which have both
14        # the new and old version of Python, but where the newer is default.
15        # This is because packages, libraries, etc are all installed into the
16        # new one by default. Some things (like running under mod_python) just
17        # plain don't handle python restarting properly. I know that I do some
18        # development under ipython and whenever I run (or do anything that
19        # runs) 'import common' it restarts my shell. Overall, the change was
20        # fairly annoying for me (and I can't get around having 2.4 and 2.5
21        # installed with 2.5 being default).
22        if not version or version < (2, 4) or version >= (3, 0):
23            try:
24                # We can't restart when running under mod_python.
25                from mod_python import apache
26            except ImportError:
27                self.restart()
28
29
30    def extract_version(self, path):
31        match = re.search(r'/python(\d+)\.(\d+)$', path)
32        if match:
33            return (int(match.group(1)), int(match.group(2)))
34        else:
35            return None
36
37
38    PYTHON_BIN_GLOB_STRINGS = ['/usr/bin/python2*', '/usr/local/bin/python2*']
39
40
41    def find_desired_python(self):
42        """Returns the path of the desired python interpreter."""
43        pythons = []
44        for glob_str in self.PYTHON_BIN_GLOB_STRINGS:
45            pythons.extend(glob.glob(glob_str))
46
47        possible_versions = []
48        best_python = (0, 0), ''
49        for python in pythons:
50            version = self.extract_version(python)
51            if version >= (2, 4):
52                possible_versions.append((version, python))
53
54        possible_versions.sort()
55
56        if not possible_versions:
57            raise ValueError('Python 2.x version 2.4 or better is required')
58        # Return the lowest possible version so that we use 2.4 if available
59        # rather than more recent versions.
60        return possible_versions[0][1]
61
62
63    def restart(self):
64        python = self.find_desired_python()
65        sys.stderr.write('NOTE: %s switching to %s\n' %
66                         (os.path.basename(sys.argv[0]), python))
67        sys.argv.insert(0, '-u')
68        sys.argv.insert(0, python)
69        os.execv(sys.argv[0], sys.argv)
70