setup_util.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import re
  2. import os
  3. import sys
  4. import subprocess
  5. import platform
  6. from threading import Thread
  7. from Queue import Queue, Empty
  8. class NonBlockingStreamReader:
  9. '''
  10. Enables calling readline in a non-blocking manner with a blocking stream,
  11. such as the ones returned from subprocess.Popen
  12. Originally written by Eyal Arubas, who granted permission to use this inside TFB
  13. See http://eyalarubas.com/python-subproc-nonblock.html
  14. '''
  15. def __init__(self, stream, eof_message = None):
  16. '''
  17. stream: the stream to read from.
  18. Usually a process' stdout or stderr.
  19. eof_message: A message to print to stdout as soon
  20. as the stream's end is reached. Useful if you
  21. want to track the exact moment a stream terminates
  22. '''
  23. self._s = stream
  24. self._q = Queue()
  25. self._eof_message = eof_message
  26. self._poisonpill = 'MAGIC_POISONPILL_STRING'
  27. def _populateQueue(stream, queue):
  28. while True:
  29. line = stream.readline()
  30. if line: # 'data\n' or '\n'
  31. queue.put(line)
  32. else: # '' e.g. EOF
  33. if self._eof_message:
  34. sys.stdout.write(self._eof_message + '\n')
  35. queue.put(self._poisonpill)
  36. return
  37. self._t = Thread(target = _populateQueue,
  38. args = (self._s, self._q))
  39. self._t.daemon = True
  40. self._t.start()
  41. def readline(self, timeout = None):
  42. try:
  43. line = self._q.get(block = timeout is not None,
  44. timeout = timeout)
  45. if line == self._poisonpill:
  46. raise EndOfStream
  47. return line
  48. except Empty:
  49. return None
  50. class EndOfStream(Exception): pass
  51. # Replaces all text found using the regular expression to_replace with the supplied replacement.
  52. def replace_text(file, to_replace, replacement):
  53. with open(file, "r") as conf:
  54. contents = conf.read()
  55. replaced_text = re.sub(to_replace, replacement, contents)
  56. with open(file, "w") as f:
  57. f.write(replaced_text)
  58. # Queries the shell for the value of FWROOT
  59. def get_fwroot():
  60. if os.getenv('FWROOT'):
  61. return os.environ['FWROOT']
  62. else:
  63. return os.getcwd()
  64. # Turns absolute path into path relative to FWROOT
  65. # Assumes path is underneath FWROOT, not above
  66. #
  67. # Useful for clean presentation of paths
  68. # e.g. /foo/bar/benchmarks/go/install.sh
  69. # v.s. FWROOT/go/install.sh
  70. def path_relative_to_root(path):
  71. # Requires bash shell parameter expansion
  72. return subprocess.check_output("D=%s && printf \"${D#%s}\""%(path, get_fwroot()), shell=True, executable='/bin/bash')