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