Skip to content

Instantly share code, notes, and snippets.

@teju85
Created October 8, 2020 10:15
Show Gist options
  • Save teju85/8cce5ae0da383cbe12f6d29c622b8d29 to your computer and use it in GitHub Desktop.
Save teju85/8cce5ae0da383cbe12f6d29c622b8d29 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import argparse
import subprocess
def runcmd(cmd):
out = "CMD:\n" + cmd
out += "OUTPUT:\n"
try:
out += subprocess.check_output(cmd, shell=True,
stderr=subprocess.STDOUT)
status = 0
except subprocess.CalledProcessError as cpe:
out += cpe.output
out += "exit-code: " + str(cpe.returncode) + "\n"
status = 1
return out, status
def validate_args(args):
pass
def parse_args():
desc = "Wrapper to run scripts and send their outputs via email"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("-mailto", default=[], action="append", type=str,
help="List of email ID's in the To of the email")
parser.add_argument("-subject", default=None, type=str,
help="Subject of the email")
parser.add_argument("script", type=str, help="Script to run (abs path)")
args = parser.parse_args()
validate_args(args)
return args
def send_mail(args, output):
if len(args.mailto) <= 0:
return
subject = args.script if args.subject is None else args.subject
pipe = subprocess.Popen(
["mail", "-s", "\"%s\"" % subject, ";".join(args.mailto)],
stdin=subprocess.PIPE)
pipe.stdin.write(output + "\n")
pipe.stdin.flush()
return
def main():
args = parse_args()
out, status = runcmd(args.script)
send_mail(args, out)
return
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment