Last active
June 26, 2017 11:49
-
-
Save inesusvet/09b403026793ce2e255ee269642f0473 to your computer and use it in GitHub Desktop.
Restarts the target process when it exits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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