首页 > 其他 > 详细

使用自定义Timer类来管理限制Subprocess的运行时间

时间:2021-04-14 15:45:45      阅读:15      评论:0      收藏:0      [点我收藏+]
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()

使用自定义Timer类来管理限制Subprocess的运行时间

原文:https://www.cnblogs.com/Ghostant/p/14656768.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!