Created
September 4, 2017 19:09
-
-
Save inesusvet/6b5c99d4730b0c9c03751c63c8c6710c to your computer and use it in GitHub Desktop.
Kill child by timeout
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 kills the command affter timeout. | |
You can specify the timeout in seconds for kill by env-variable TIMEOUT | |
Example: | |
TIMEOUT=300 python time-keeper.py this-will-hang-up-but-gonna-be-killed-in-5-mins.exe | |
""" | |
import logging | |
import os | |
import subprocess | |
import sys | |
import time | |
logging.basicConfig( | |
level=logging.INFO, | |
format='%(asctime)s %(levelname)s %(message)s', | |
datefmt='%Y-%m-%d %H:%M:%S', | |
filename='time-keeper.log', | |
) | |
logger = logging.getLogger(__name__) | |
def run(cmd): | |
logger.info('Run process: %s', ' '.join(cmd)) | |
return subprocess.Popen(cmd) | |
def main(cmd, timeout=10, exit_code=0): | |
start = time.time() | |
pipe = run(cmd) | |
while True: | |
return_code = pipe.poll() | |
if return_code is not None: | |
return return_code | |
elif (time.time() - start) < timeout: | |
time.sleep(1) | |
continue | |
pipe.kill() | |
return exit_code | |
if __name__ == '__main__': | |
if len(sys.argv) < 2: | |
print(__doc__) | |
exit(1) | |
cmd = sys.argv[1:] | |
timeout = int(os.environ.get('TIMEOUT', 10)) | |
exit(main(cmd, timeout=timeout)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment