Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from datetime import datetime
- import subprocess
- import sys
- log_file = __file__
- def log(message):
- """
- :type message:str
- """
- time_format = "%d-%b %H:%M:%S"
- now = datetime.now().strftime(time_format)
- formatted = "{}: {}".format(now, message)
- print(formatted)
- with open(log_file, "a+") as f:
- f.write(formatted + "\n")
- def execute(cmd, raise_exception=True, **kwargs):
- """
- :param raise_exception: not raise exception if non-zero return code is expected
- :type cmd:str
- """
- if len(kwargs) != 0:
- log("Execute cmd: <{}> with kwargs:<{}>".format(cmd, kwargs))
- else:
- log("Execute cmd: <{}>".format(cmd))
- cmd = cmd.split(" ")
- pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
- stdout, stderror = pipe.communicate()
- returncode = pipe.returncode
- if stdout != "" and stdout is not None:
- log("{0} Begin stdout {0}".format("*" * 30))
- with open(log_file, "a+") as f:
- sys.stdout.writelines(stdout)
- f.writelines(stdout)
- log("{0} End stdout {0}".format("*" * 30))
- if returncode != 0:
- if stderror != "" and stderror is not None:
- log("{0} Begin stderr {0}".format("*" * 30))
- log("Non-zero code returned <{}>".format(returncode))
- with open(log_file, "a+") as f:
- sys.stdout.writelines(stderror)
- f.writelines(stderror)
- log("{0} End stderr {0}".format("*" * 30))
- if raise_exception:
- raise subprocess.CalledProcessError(returncode, cmd)
- else:
- return False
- else:
- return True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement