PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/setup/install_tools.py

http://github.com/aichallenge/aichallenge
Python | 122 lines | 103 code | 12 blank | 7 comment | 17 complexity | d2c36bfeca9cdbe07d28442110bda074 MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause
  1. import getpass
  2. import os
  3. import re
  4. from subprocess import Popen, PIPE
  5. class Environ(object):
  6. """ Context manager that sets and restores an environment variable """
  7. def __init__(self, var, value):
  8. self.env_var = var
  9. self.new_value = value
  10. def __enter__(self):
  11. self.start_value = os.environ.get(self.env_var, None)
  12. os.environ[self.env_var] = self.new_value
  13. return self.new_value
  14. def __exit__(self, type, value, traceback):
  15. if self.start_value is not None:
  16. os.environ[self.env_var] = self.start_value
  17. else:
  18. del os.environ[self.env_var]
  19. class CD(object):
  20. """ Context manager to change and restore the current working directory """
  21. def __init__(self, new_dir):
  22. self.new_dir = new_dir
  23. def __enter__(self):
  24. self.org_dir = os.getcwd()
  25. os.chdir(self.new_dir)
  26. return self.new_dir
  27. def __exit__(self, type, value, traceback):
  28. os.chdir(self.org_dir)
  29. def file_contains(filename, line_pattern):
  30. """ Checks if a file has a line matching the given pattern """
  31. if not os.path.exists(filename):
  32. return False
  33. regex = re.compile(line_pattern)
  34. with open(filename, 'r') as src:
  35. for line in src:
  36. if regex.search(line):
  37. return True
  38. return False
  39. def append_line(filename, line):
  40. """ Appends a line to a file """
  41. with open(filename, "a+") as afile:
  42. afile.write(line + '\n')
  43. class CmdError(StandardError):
  44. """ Exception raised on an error return code results from run_cmd """
  45. def __init__(self, cmd, returncode):
  46. self.cmd = cmd
  47. self.returncode = returncode
  48. StandardError.__init__(self, "Error %s returned from %s"
  49. % (returncode, cmd))
  50. def run_cmd(cmd, capture_stdout=False):
  51. """ Run a command in a shell """
  52. print "Executing:", cmd
  53. stdout_loc = PIPE if capture_stdout else None
  54. proc = Popen(cmd, shell=True, stdout=stdout_loc)
  55. output, error_out = proc.communicate()
  56. status = proc.wait()
  57. if status != 0:
  58. raise CmdError(cmd, status)
  59. return output
  60. def install_apt_packages(packages):
  61. """ Install system packages using aptitude """
  62. apt_cmd = "apt-get install -y "
  63. try:
  64. cmd = apt_cmd + packages
  65. except TypeError:
  66. cmd = apt_cmd + " ".join(packages)
  67. run_cmd(cmd)
  68. def get_choice(query, default=False):
  69. negative_responses = ["no", "n"]
  70. positive_responses = ["yes", "y"]
  71. query += " [%s] " % ('yes' if default else 'no')
  72. while True:
  73. resp = raw_input(query).lower().strip()
  74. if resp in negative_responses or (resp == "" and not default):
  75. return False
  76. if resp in positive_responses or (resp == "" and default):
  77. return True
  78. def get_password(pw_name):
  79. while True:
  80. passwd = getpass.getpass("%s password? " % (pw_name.capitalize()))
  81. confirm = getpass.getpass("Confirm %s password? " % (pw_name,))
  82. if passwd == confirm:
  83. return passwd
  84. print "Sorry, passwords did not match."
  85. def get_ubuntu_release_info():
  86. version="notubuntu"
  87. arch="unknown"
  88. try:
  89. version=re.match(".*DISTRIB_CODENAME=(\w*).*",open("/etc/lsb-release").read(),re.DOTALL).group(1)
  90. arch=run_cmd("dpkg --print-architecture",True).strip()
  91. except CmdError, IOError:
  92. arch=run_cmd("uname -p",True).strip()
  93. except:
  94. pass
  95. return version, arch
  96. def check_ubuntu_version():
  97. version,arch=get_ubuntu_release_info()
  98. if version!="notubuntu":
  99. print "Install tools on Ubuntu version:%s arch:%s." % (version, arch)
  100. else:
  101. print "Installing on an %s non-Ubuntu host." % (arch)
  102. if version!="natty":
  103. raise Exception("This contest framework was designed to work on Ubuntu Natty(11.04) only.")
  104. return version, arch