Advertisement
Guest User

Untitled

a guest
Jan 24th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. from datetime import datetime
  2. import subprocess
  3. import sys
  4.  
  5. log_file = __file__
  6.  
  7.  
  8. def log(message):
  9. """
  10. :type message:str
  11. """
  12. time_format = "%d-%b %H:%M:%S"
  13. now = datetime.now().strftime(time_format)
  14. formatted = "{}: {}".format(now, message)
  15. print(formatted)
  16. with open(log_file, "a+") as f:
  17. f.write(formatted + "\n")
  18.  
  19.  
  20. def execute(cmd, raise_exception=True, **kwargs):
  21. """
  22. :param raise_exception: not raise exception if non-zero return code is expected
  23. :type cmd:str
  24. """
  25. if len(kwargs) != 0:
  26. log("Execute cmd: <{}> with kwargs:<{}>".format(cmd, kwargs))
  27. else:
  28. log("Execute cmd: <{}>".format(cmd))
  29.  
  30. cmd = cmd.split(" ")
  31. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
  32. stdout, stderror = pipe.communicate()
  33. returncode = pipe.returncode
  34.  
  35. if stdout != "" and stdout is not None:
  36. log("{0} Begin stdout {0}".format("*" * 30))
  37. with open(log_file, "a+") as f:
  38. sys.stdout.writelines(stdout)
  39. f.writelines(stdout)
  40. log("{0} End stdout {0}".format("*" * 30))
  41.  
  42. if returncode != 0:
  43.  
  44. if stderror != "" and stderror is not None:
  45. log("{0} Begin stderr {0}".format("*" * 30))
  46. log("Non-zero code returned <{}>".format(returncode))
  47. with open(log_file, "a+") as f:
  48. sys.stdout.writelines(stderror)
  49. f.writelines(stderror)
  50. log("{0} End stderr {0}".format("*" * 30))
  51.  
  52. if raise_exception:
  53. raise subprocess.CalledProcessError(returncode, cmd)
  54.  
  55. else:
  56. return False
  57. else:
  58. return True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement