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全局变量操作详解
Apr 14 Python
python操作ie登陆土豆网的方法
May 09 Python
Python实现类似jQuery使用中的链式调用的示例
Jun 16 Python
python添加模块搜索路径方法
Sep 11 Python
Python实现的远程登录windows系统功能示例
Jun 21 Python
解决Python print 输出文本显示 gbk 编码错误问题
Jul 13 Python
python 定时器每天就执行一次的实现代码
Aug 14 Python
python tornado使用流生成图片的例子
Nov 18 Python
Python3 中作为一等对象的函数解析
Dec 11 Python
Django多进程滚动日志问题解决方案
Dec 17 Python
Python函数默认参数常见问题及解决方案
Mar 26 Python
python3.x中安装web.py步骤方法
Jun 23 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抽象类 介绍
2012/06/13 PHP
php class类的用法详细总结
2013/10/17 PHP
php打印一个边长为N的实心和空心菱型的方法
2015/03/02 PHP
Nginx服务器上安装并配置PHPMyAdmin的教程
2015/08/18 PHP
JS 参数传递的实际应用代码分析
2009/09/13 Javascript
javascript Keycode对照表
2009/10/24 Javascript
JavaScript isArray()函数判断对象类型的种种方法
2010/10/11 Javascript
jquery.map()方法的使用详解
2015/07/09 Javascript
xcode中获取js文件的路径方法(推荐)
2016/11/05 Javascript
Bootstrap CSS组件之导航条(navbar)
2016/12/17 Javascript
JavaScript获取中英文混合字符串长度的方法示例
2017/02/04 Javascript
JavaScript内存泄漏的处理方式
2017/11/20 Javascript
layui实现table加载的示例代码
2018/08/14 Javascript
优雅的处理vue项目异常实战记录
2019/06/05 Javascript
微信小程序 调用微信授权窗口相关问题解决
2019/07/25 Javascript
Vue分页插件的前后端配置与使用
2019/10/09 Javascript
[42:20]Secret vs Liquid 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/17 DOTA
Python中在脚本中引用其他文件函数的实现方法
2016/06/23 Python
TensorFlow Session会话控制&amp;Variable变量详解
2018/07/30 Python
对python 通过ssh访问数据库的实例详解
2019/02/19 Python
python实现各种插值法(数值分析)
2019/07/30 Python
使用Python求解带约束的最优化问题详解
2020/02/11 Python
css3动画效果小结(推荐)
2016/07/25 HTML / CSS
iframe与window.onload如何使用详解
2020/05/07 HTML / CSS
领先的钻石和订婚戒指零售商:Diamonds-USA
2016/12/11 全球购物
Python的两道面试题
2013/06/29 面试题
Structs界面控制层技术
2013/10/11 面试题
学术会议主持词
2014/03/17 职场文书
保护环境倡议书范文
2014/05/13 职场文书
五水共治一句话承诺
2014/05/30 职场文书
重阳节活动总结
2014/08/27 职场文书
买房协议书范本
2014/10/23 职场文书
平安家庭事迹材料
2014/12/20 职场文书
2015年数学教师工作总结
2015/05/20 职场文书
学校运动会简讯
2015/07/20 职场文书
Python实现信息轰炸工具(再也不怕说不过别人了)
2021/06/11 Python