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和C语言混合编程实例
Jun 04 Python
浅谈numpy库的常用基本操作方法
Jan 09 Python
python批量替换页眉页脚实例代码
Jan 22 Python
Flask 让jsonify返回的json串支持中文显示的方法
Mar 26 Python
Python+selenium实现自动循环扔QQ邮箱漂流瓶
May 29 Python
Python实现提取XML内容并保存到Excel中的方法
Sep 01 Python
基于python的列表list和集合set操作
Nov 24 Python
tensorflow之变量初始化(tf.Variable)使用详解
Feb 06 Python
pyecharts绘制中国2020肺炎疫情地图的实例代码
Feb 12 Python
Python unittest单元测试openpyxl实现过程解析
May 27 Python
如何利用python 读取配置文件
Jan 06 Python
Python实现数据的序列化操作详解
Jul 07 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实现的DES加密解密类定义与用法示例
2020/11/02 PHP
jquery ajax提交表单数据的两种实现方法
2010/04/29 Javascript
DB.ASP 用Javascript写ASP很灵活很好用很easy
2011/07/31 Javascript
Javascript的各种节点操作实例演示代码
2012/06/27 Javascript
JS实现商品倒计时实现代码
2013/05/03 Javascript
js 获取、清空input type=&quot;file&quot;的值示例代码
2014/02/19 Javascript
JQuery 图片滚动轮播示例代码
2014/03/24 Javascript
使用jquery解析XML的方法
2014/09/05 Javascript
jQuery中:contains选择器用法实例
2014/12/30 Javascript
在for循环中length值是否需要缓存
2015/07/27 Javascript
基于jquery插件实现拖拽删除图片功能
2020/08/27 Javascript
内容滑动切换效果jquery.hwSlide.js插件封装
2016/07/07 Javascript
Bootstrap企业网站实战项目4
2016/10/14 Javascript
js正则表达式最长匹配(贪婪匹配)和最短匹配(懒惰匹配)用法分析
2016/12/27 Javascript
jQuery如何跳转到另一个网页 就这么简单
2016/12/28 Javascript
Vue数据驱动模拟实现3
2017/01/11 Javascript
移动端基础事件总结与应用
2017/01/12 Javascript
BootStrap实现鼠标悬停下拉列表功能
2017/02/17 Javascript
激动人心的 Angular HttpClient的源码解析
2017/07/10 Javascript
在vue中获取dom元素内容的方法
2017/07/10 Javascript
详解easyui基于 layui.laydate日期扩展组件
2018/07/18 Javascript
js实现类似iphone的网页滑屏解锁功能示例【附源码下载】
2019/06/10 Javascript
Python中有趣在__call__函数
2015/06/21 Python
Python内置模块ConfigParser实现配置读写功能的方法
2018/02/12 Python
python实现百度OCR图片识别过程解析
2020/01/17 Python
python实现贪吃蛇游戏源码
2020/03/21 Python
开放系统互连参考模型
2016/06/29 面试题
高中地理教学反思
2014/01/29 职场文书
《在山的那边》教学反思
2014/02/23 职场文书
文明之星事迹材料
2014/05/09 职场文书
商场促销活动总结
2014/07/10 职场文书
安全标兵事迹材料
2014/08/17 职场文书
教师廉洁自律个人总结
2015/02/10 职场文书
业务员年终工作总结2015
2015/05/28 职场文书
单位工作证明范本
2015/06/15 职场文书
python基础之while循环语句的使用
2021/04/20 Python