Skip to content

Instantly share code, notes, and snippets.

@inesusvet
Last active June 26, 2017 11:49
Show Gist options
  • Save inesusvet/09b403026793ce2e255ee269642f0473 to your computer and use it in GitHub Desktop.
Save inesusvet/09b403026793ce2e255ee269642f0473 to your computer and use it in GitHub Desktop.
Restarts the target process when it exits
"""
Simple watchdog which just restarts the command.
You can specify the limit for restarts by env-variable LIMIT
Example:
LIMIT=10 python watchdog.py this_may_fall.exe
"""
import logging
import os
import subprocess
import sys
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='watchdog.log',
)
logger = logging.getLogger(__name__)
def run_and_wait(cmd):
logger.info('Run process: %s', ' '.join(cmd))
pipe = subprocess.Popen(cmd)
exit_code = pipe.wait()
logger.info('Process exit with code %d', exit_code)
def main(cmd, limit=0):
n = 0
if limit == 0:
condition = lambda _: True
else:
condition = lambda i: i < limit
while condition(n):
run_and_wait(cmd)
if limit != 0:
n += 1
if __name__ == '__main__':
if len(sys.argv) < 2:
print(__doc__)
exit(1)
cmd = sys.argv[1:]
limit = int(os.environ.get('LIMIT', 0))
exit(main(cmd, limit=limit))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment