/client/common_lib/base_check_version.py

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