util.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/python
  2. # Licensed to the Apache Software Foundation (ASF) under one or more
  3. # contributor license agreements. See the NOTICE file distributed with
  4. # this work for additional information regarding copyright ownership.
  5. # The ASF licenses this file to You under the Apache License, Version 2.0
  6. # (the "License"); you may not use this file except in compliance with
  7. # the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import time
  17. import re
  18. import logging
  19. import subprocess
  20. logger = logging.getLogger(__name__)
  21. def wait_until(predicate, timeout, check_frequency=1):
  22. deadline = time.time() + timeout
  23. while time.time() < deadline:
  24. if predicate():
  25. return
  26. time.sleep(check_frequency)
  27. def run_cmd(cmd):
  28. command = cmd
  29. if isinstance(cmd, list):
  30. command = ' '.join(cmd)
  31. logger.info(" RUNNING: %s", command)
  32. all_output = ""
  33. my_process = subprocess.Popen(command, stdout=subprocess.PIPE,
  34. stderr=subprocess.STDOUT, shell=True)
  35. while my_process.poll() is None:
  36. op = my_process.stdout.readline()
  37. if op:
  38. all_output += op
  39. logger.info(op)
  40. other_output = my_process.communicate()
  41. other_output = other_output[0].strip()
  42. if other_output != "":
  43. all_output += other_output
  44. reg = re.compile(r"(\r\n|\n)$")
  45. all_output = reg.sub("", all_output, 1)
  46. return my_process.returncode, all_output