zoukankan      html  css  js  c++  java
  • 使用自定义Timer类来管理限制Subprocess的运行时间

    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()
    
  • 相关阅读:
    python处理excel文件
    Python datetime模块
    OrderedDict 有序字典以及读取json串时如何保持原有顺序
    ansible 学习笔记
    nginx的location和rewrite
    实体机重装系统
    热词
    教育
    生活
    1、两数之和
  • 原文地址:https://www.cnblogs.com/Ghostant/p/14656768.html
Copyright © 2011-2022 走看看