import threading
import time
import logging
class TimeoutWrapper(object):
def __init__(self, timeout, process):
self.timeout = timeout
self.timer = None
self.process = process
self.timeout_encountered = False
self.logger = logging.getLogger(__name__)
def _timer_func(self):
self.timeout_encountered = True
self.logger.info("Terminate subprocess;PID=%d...", self.process.pid)
self.process.terminated()
for i in range(10):
if self.process.poll() is not None:
return
self.logger.warn("Subprocess is still alive; waiting...")
time.sleep(0.5)
self.logger.warn("Subprocess still alive; sending KILL signal")
self.logger.warning("Subprocess killed")
def __enter__(self):
if self.timeout:
self.timer = threading.Timer(self.timeout, self._timer_func)
self.timer.start()
def __exit__(self, exc_type, exc_val, exc_tb):
if self.timer:
self.timer.cancel()