import sys
import threading
class StoppablePythonThread(threading.Thread):
"""A subclass of threading.Thread, with a stop() method.
Original version posted by Connelly Barnes to python-list and available at
This version mainly has kill() changed to stop() to match java.lang.Thread.
This is a hack but seems to be the best way the get this done. Only used
in Python because in Jython we can use java.lang.Thread.
"""
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
self._stopped = False
def start(self):
"""Start the thread."""
self.__run_backup = self.run
self.run = self.__run # Force the Thread to install our trace.
threading.Thread.start(self)
def stop(self):
self._stopped = True
def __run(self):
"""Hacked run function, which installs the trace."""
sys.settrace(self._globaltrace)
self.__run_backup()
self.run = self.__run_backup
def _globaltrace(self, frame, why, arg):
if why == 'call':
return self._localtrace
else:
return None
def _localtrace(self, frame, why, arg):
if self._stopped:
if why == 'line':
raise SystemExit()
return self._localtrace
文件路径:C:\Python26\lib\site-packages\robot\stoppablethread.py
功能:用于python平台上停止线程,使用的地方不多,暂不深入。
阅读(23447) | 评论(0) | 转发(0) |