1# This file must use Python 1.5 syntax. 2import glob 3import os 4import sys 5 6 7class check_python_version: 8 9 def __init__(self): 10 # In order to ease the migration to Python3, disable the restart logic 11 # when AUTOTEST_NO_RESTART is set. This makes it possible to run 12 # autotest locally as Python3 before any other environment is switched 13 # to Python3. 14 if os.getenv("AUTOTEST_NO_RESTART"): 15 return 16 17 # The change to prefer 2.4 really messes up any systems which have both 18 # the new and old version of Python, but where the newer is default. 19 # This is because packages, libraries, etc are all installed into the 20 # new one by default. Some things (like running under mod_python) just 21 # plain don't handle python restarting properly. I know that I do some 22 # development under ipython and whenever I run (or do anything that 23 # runs) 'import common' it restarts my shell. Overall, the change was 24 # fairly annoying for me (and I can't get around having 2.4 and 2.5 25 # installed with 2.5 being default). 26 if sys.version_info.major >= 3: 27 try: 28 # We can't restart when running under mod_python. 29 from mod_python import apache 30 except ImportError: 31 self.restart() 32 33 34 PYTHON_BIN_GLOB_STRINGS = ['/usr/bin/python2*', '/usr/local/bin/python2*'] 35 36 37 def find_desired_python(self): 38 """Returns the path of the desired python interpreter.""" 39 # CrOS only ever has Python 2.7 available, so pick whatever matches. 40 pythons = [] 41 for glob_str in self.PYTHON_BIN_GLOB_STRINGS: 42 pythons.extend(glob.glob(glob_str)) 43 return pythons[0] 44 45 46 def restart(self): 47 python = self.find_desired_python() 48 sys.stderr.write('NOTE: %s switching to %s\n' % 49 (os.path.basename(sys.argv[0]), python)) 50 sys.argv.insert(0, '-u') 51 sys.argv.insert(0, python) 52 os.execv(sys.argv[0], sys.argv) 53