procutil.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # -*- coding: utf-8 -*-
  2. import subprocess
  3. import logging
  4. logger = logging.getLogger(__name__)
  5. def subproc_call(cmd, timeout=None):
  6. """
  7. Execute a command with timeout, and return STDOUT and STDERR
  8. Args:
  9. cmd(str): the command to execute.
  10. timeout(float): timeout in seconds.
  11. Returns:
  12. output(bytes), retcode(int). If timeout, retcode is -1.
  13. """
  14. try:
  15. output = subprocess.check_output(
  16. cmd, stderr=subprocess.STDOUT,
  17. shell=True, timeout=timeout)
  18. return output, 0
  19. except subprocess.TimeoutExpired as e:
  20. logger.warn("Command '{}' timeout!".format(cmd))
  21. if e.output:
  22. logger.warn(e.output.decode('utf-8'))
  23. return e.output, -1
  24. else:
  25. return "", -1
  26. except subprocess.CalledProcessError as e:
  27. logger.warn("Command '{}' failed, return code={}".format(cmd, e.returncode))
  28. logger.warn(e.output.decode('utf-8'))
  29. return e.output, e.returncode
  30. except Exception:
  31. logger.warn("Command '{}' failed to run.".format(cmd))
  32. return "", -2
  33. def subproc_succ(cmd):
  34. """
  35. Like subproc_call, but expect the cmd to succeed.
  36. """
  37. output, ret = subproc_call(cmd)
  38. assert ret == 0
  39. return output