#!/usr/bin/env python3 import sys # print(sys.path) from sys import argv import socket from typing import List from exec_notify.lib import exec, mail, util def main(): """ Usage: exec-notify with command = [ ...] :return: exit code of executed command """ if len(argv) <= 1: print('No command given to execute!', file=sys.stderr) exit(1) exit(executeCommand(argv[1:])) def executeCommand(command: List[str]) -> int: """ Executes the given command and sends an email on failure. :return: exit code of executed command """ try: exitCode, stdout, stderr = exec.execute(command) except Exception as e: exitCode, stdout, stderr = 1, '', 'Caught subprocess exception: ' + str(e) prefix = '┃ ' BODY = f'┏{"━" * 19}\n' \ f'┣╸Command:\n' \ f'{util.appendLinePrefix(prefix, str(command))}\n' \ f'┣╸Exit Code:\n' \ f'{util.appendLinePrefix(prefix, str(exitCode))}\n' \ f'┣╸stderr:\n' \ f'{util.appendLinePrefix(prefix, stderr)}\n' \ f'┣╸stdout:\n' \ f'{util.appendLinePrefix(prefix, stdout)}\n' \ f'┗{"━" * 19}' print(BODY) if exitCode != 0: SUBJECT = f'{socket.gethostname()} | {str(command)}' mail.sendMailOrWriteToFile(SUBJECT=SUBJECT, BODY=BODY) return exitCode if __name__ == '__main__': main()