python杀死一个线程的方法


Posted in Python onSeptember 06, 2015

最近在项目中遇到这一需求:

我需要一个函数工作,比如远程连接一个端口,远程读取文件等,但是我给的时间有限,比如,4秒钟如果你还没有读取完成或者连接成功,我就不等了,很可能对方已经宕机或者拒绝了。这样可以批量做一些事情而不需要一直等,浪费时间。

结合我的需求,我想到这种办法:

1、在主进程执行,调用一个进程执行函数,然后主进程sleep,等时间到了,就kill 执行函数的进程。

测试一个例子:

import time 
import threading 
def p(i): 
  print i 
class task(threading.Thread): 
  def __init__(self,fun,i): 
    threading.Thread.__init__(self) 
    self.fun = fun 
    self.i = i 
    self.thread_stop = False 
  def run(self): 
    while not self.thread_stop: 
      self.fun(self.i) 
  def stop(self): 
    self.thread_stop = True 
def test(): 
  thread1 = task(p,2) 
  thread1.start() 
  time.sleep(4) 
  thread1.stop() 
  return 
if __name__ == '__main__': 
  test()

经过测试只定了4秒钟。

经过我的一番折腾,想到了join函数,这个函数式用来等待一个线程结束的,如果这个函数没有结束的话,那么,就会阻塞当前运行的程序。关键是,这个参数有一个可选参数:join([timeout]):  阻塞当前上下文环境的线程,直到调用此方法的线程终止或到达指定的timeout(可选参数)。

不多说了贴下面代码大家看下:

#!/usr/bin/env python 
#-*-coding:utf-8-*- 
''''' 
author:cogbee 
time:2014-6-13 
function:readme 
''' 
import pdb 
import time 
import threading 
import os 
#pdb.set_trace() 
class task(threading.Thread): 
  def __init__(self,ip): 
    threading.Thread.__init__(self) 
    self.ip = ip 
    self.thread_stop = False 
  def run(self): 
    while not self.thread_stop:   
      #//添加你要做的事情,如果成功了就设置一下<span style="font-family: Arial, Helvetica, sans-serif;">self.thread_stop变量。</span> 
[python] view plaincopy在CODE上查看代码片派生到我的代码片
      if file != '': 
        self.thread_stop = True 
  def stop(self): 
    self.thread_stop = True 
def test(eachline): 
  global file 
  list = [] 
  for ip in eachline: 
    thread1 = task(ip) 
    thread1.start() 
    thread1.join(3) 
    if thread1.isAlive():   
      thread1.stop() 
      continue 
    #将可以读取的都存起来 
    if file != '': 
      list.append(ip) 
  print list 
if __name__ == '__main__': 
  eachline = ['1.1.1.1','222.73.5.54'] 
  test(eachline)

下面给大家分享我写的一段杀死线程的代码。

由于python线程没有提供abort方法,分享下面一段代码杀死线程:

import threading 
import inspect 
import ctypes 
def _async_raise(tid, exctype):
  """raises the exception, performs cleanup if needed"""
  if not inspect.isclass(exctype):
    raise TypeError("Only types can be raised (not instances)")
  res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
  if res == 0:
    raise ValueError("invalid thread id")
  elif res != 1:
    # """if it returns a number greater than one, you're in trouble, 
    # and you should call it again with exc=NULL to revert the effect"""
    ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
    raise SystemError("PyThreadState_SetAsyncExc failed")
class Thread(threading.Thread):
  def _get_my_tid(self):
    """determines this (self's) thread id"""
    if not self.isAlive():
      raise threading.ThreadError("the thread is not active")
    # do we have it cached?
    if hasattr(self, "_thread_id"):
      return self._thread_id
    # no, look for it in the _active dict
    for tid, tobj in threading._active.items():
      if tobj is self:
        self._thread_id = tid
        return tid
    raise AssertionError("could not determine the thread's id")
def raise_exc(self, exctype):
    """raises the given exception type in the context of this thread"""
    _async_raise(self._get_my_tid(), exctype)
def terminate(self):
    """raises SystemExit in the context of the given thread, which should 
    cause the thread to exit silently (unless caught)"""
    self.raise_exc(SystemExit)

使用例子:

>>> import time 
>>> from thread2 import Thread 
>>> 
>>> def f(): 
...   try: 
...     while True: 
...       time.sleep(0.1) 
...   finally: 
...     print "outta here" 
... 
>>> t = Thread(target = f) 
>>> t.start() 
>>> t.isAlive() 
True 
>>> t.terminate() 
>>> t.join() 
outta here 
>>> t.isAlive() 
False

试了一下,很不错,只是在要kill的线程中如果有time.sleep()时,好像工作不正常,没有找出真正的原因是什么。已经是很强大了。哈哈。

Python 相关文章推荐
python使用正则表达式分析网页中的图片并进行替换的方法
Mar 26 Python
python在linux系统下获取系统内存使用情况的方法
May 11 Python
Python3.5.3下配置opencv3.2.0的操作方法
Apr 02 Python
Python设计模式之组合模式原理与用法实例分析
Jan 11 Python
Python如何调用JS文件中的函数
Aug 16 Python
Python图像处理模块ndimage用法实例分析
Sep 05 Python
解决Keras 与 Tensorflow 版本之间的兼容性问题
Feb 07 Python
Python unittest 自动识别并执行测试用例方式
Mar 09 Python
Django 自定义权限管理系统详解(通过中间件认证)
Mar 11 Python
Python实现迪杰斯特拉算法过程解析
Sep 18 Python
基于Python爬取股票数据过程详解
Oct 21 Python
在Python的Flask框架中验证注册用户的Email的方法
Sep 02 #Python
Python实现身份证号码解析
Sep 01 #Python
实例Python处理XML文件的方法
Aug 31 #Python
通过实例浅析Python对比C语言的编程思想差异
Aug 30 #Python
使用Python脚本将文字转换为图片的实例分享
Aug 29 #Python
Python中常见的数据类型小结
Aug 29 #Python
深入解析Python中的lambda表达式的用法
Aug 28 #Python
You might like
PHP实现加密的几种方式介绍
2015/02/22 PHP
PHP url的pathinfo模式加载不同控制器的简单实现
2016/08/12 PHP
javascript循环变量注册dom事件 之强大的闭包
2010/09/08 Javascript
jquery 选择器引擎sizzle浅析
2013/02/06 Javascript
7款吸引人眼球的jQuery/CSS3特效实例分享
2013/04/25 Javascript
javascript操作table(insertRow,deleteRow,insertCell,deleteCell方法详解)
2013/12/16 Javascript
js 本地预览的简单实现方法
2014/02/18 Javascript
js的Boolean对象初始值示例
2014/03/04 Javascript
浅谈javascript中字符串String与数组Array
2014/12/31 Javascript
jquery插件qrcode在线生成二维码
2015/04/26 Javascript
javascript鼠标右键菜单自定义效果
2020/12/08 Javascript
使用JavaScript实现ajax的实例代码
2016/05/11 Javascript
Bootstrap+jfinal退出系统弹出确认框的实现方法
2016/05/30 Javascript
angularjs中使用ng-bind-html和ng-include的实例
2017/04/28 Javascript
浅析Vue自定义组件的v-model
2017/11/26 Javascript
详解webpack提取第三方库的正确姿势
2017/12/22 Javascript
javascript标准库(js的标准内置对象)总结
2018/05/26 Javascript
Vue.js 实现数据展示全部和收起功能
2018/09/05 Javascript
深入理解js A*寻路算法原理与具体实现过程
2018/12/13 Javascript
JavaScript中的null和undefined用法解析
2019/09/30 Javascript
微信小程序自定义纯净模态框(弹出框)的实例代码
2020/03/09 Javascript
[03:54]DOTA2英雄梦之声_第06期_昆卡
2014/06/23 DOTA
Python使用openpyxl读写excel文件的方法
2017/06/30 Python
将python代码和注释分离的方法
2018/04/21 Python
Python实现基于KNN算法的笔迹识别功能详解
2018/07/09 Python
使用pytorch进行图像的顺序读取方法
2018/07/27 Python
python speech模块的使用方法
2020/09/09 Python
《开国大典》教学反思
2014/04/19 职场文书
2014年教研活动总结范文
2014/04/26 职场文书
市场开发计划书
2014/05/07 职场文书
幼儿园小班见习报告
2014/10/31 职场文书
武夷山导游词
2015/02/03 职场文书
雷锋之歌观后感
2015/06/10 职场文书
浅谈@Value和@Bean的执行顺序问题
2021/06/16 Java/Android
Vue实现跑马灯样式文字横向滚动
2021/11/23 Vue.js
DIY胆机必读:各国电子管评价
2022/04/06 无线电