7
我使用依赖于SIGALRM设置报警中断配方 - Using module 'subprocess' with timeout以超时多子进程
的问题是,我使用signal.ALARM进程设置超时有一个以上的Python脚本,只有最新的警报被调用。改进这种多重Python函数设置超时的好方法是什么?
我使用依赖于SIGALRM设置报警中断配方 - Using module 'subprocess' with timeout以超时多子进程
的问题是,我使用signal.ALARM进程设置超时有一个以上的Python脚本,只有最新的警报被调用。改进这种多重Python函数设置超时的好方法是什么?
除了简单,快速的黑客,避免SIGALRM。这是一个非常陈旧,有限的机制,不适合更复杂的任何事情:您只能设置一个闹钟,并且它在当时中断任何系统调用,而不是仅打算打断该闹钟。
这是更清洁使用超时线程杀死进程,例如:
import subprocess, signal, os, threading, errno
from contextlib import contextmanager
class TimeoutThread(object):
def __init__(self, seconds):
self.seconds = seconds
self.cond = threading.Condition()
self.cancelled = False
self.thread = threading.Thread(target=self._wait)
def run(self):
"""Begin the timeout."""
self.thread.start()
def _wait(self):
with self.cond:
self.cond.wait(self.seconds)
if not self.cancelled:
self.timed_out()
def cancel(self):
"""Cancel the timeout, if it hasn't yet occured."""
with self.cond:
self.cancelled = True
self.cond.notify()
self.thread.join()
def timed_out(self):
"""The timeout has expired."""
raise NotImplementedError
class KillProcessThread(TimeoutThread):
def __init__(self, seconds, pid):
super(KillProcessThread, self).__init__(seconds)
self.pid = pid
def timed_out(self):
try:
os.kill(self.pid, signal.SIGKILL)
except OSError as e:
# If the process is already gone, ignore the error.
if e.errno not in (errno.EPERM, errno. ESRCH):
raise e
@contextmanager
def processTimeout(seconds, pid):
timeout = KillProcessThread(seconds, pid)
timeout.run()
try:
yield
finally:
timeout.cancel()
def example():
proc = subprocess.Popen(["sleep", "5"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
with processTimeout(1, proc.pid):
print proc.communicate()
resultcode = proc.wait()
if resultcode < 0:
print "error: %i" % resultcode
if __name__ == '__main__':
example()
根据您定时什么了,你可能需要使用更轻的信号不是SIGKILL允许时机完成后自行清理。