Chinaunix首页 | 论坛 | 博客
  • 博客访问: 19867009
  • 博文数量: 679
  • 博客积分: 10495
  • 博客等级: 上将
  • 技术积分: 9308
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-18 10:51
文章分类

全部博文(679)

文章存档

2012年(5)

2011年(38)

2010年(86)

2009年(145)

2008年(170)

2007年(165)

2006年(89)

分类: Python/Ruby

2010-02-09 11:31:18

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平台上停止线程,使用的地方不多,暂不深入。
阅读(23406) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~