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笔记(1) 关于我们应不应该继续学习python
Oct 24 Python
python通过ftplib登录到ftp服务器的方法
May 08 Python
python实现简单ftp客户端的方法
Jun 28 Python
Python+django实现简单的文件上传
Aug 17 Python
Python 中的with关键字使用详解
Sep 11 Python
Python 多核并行计算的示例代码
Nov 07 Python
Python干货:分享Python绘制六种可视化图表
Aug 27 Python
python3.6 如何将list存入txt后再读出list的方法
Jul 02 Python
Python利用requests模块下载图片实例代码
Aug 12 Python
使用Django搭建一个基金模拟交易系统教程
Nov 18 Python
tensorflow之并行读入数据详解
Feb 05 Python
七个非常实用的Python工具包总结
Jun 15 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 上一篇,下一篇文章实现代码与原理说明
2010/05/09 PHP
php使用number_format函数截取小数的方法分析
2016/05/27 PHP
如何使用PHP给图片加水印
2016/10/12 PHP
简单谈谈 php 文件锁
2017/02/19 PHP
Javascript UrlDecode函数代码
2010/01/09 Javascript
jQuery产品间断向下滚动效果核心代码
2014/05/08 Javascript
使用jQuery的attr方法来修改onclick值
2014/07/07 Javascript
教你如何使用node.js制作代理服务器
2014/11/26 Javascript
JavaScript中Number.MIN_VALUE属性的使用示例
2015/06/04 Javascript
解析JavaScript的ES6版本中的解构赋值
2015/07/28 Javascript
js实现圆盘记速表
2015/08/03 Javascript
Node.js 日志处理模块log4js
2016/08/28 Javascript
详解nodejs 文本操作模块-fs模块(五)
2016/12/23 NodeJs
最全正则表达式总结:验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等
2017/08/16 Javascript
vue响应式系统之observe、watcher、dep的源码解析
2019/04/09 Javascript
Elasticsearch实现复合查询高亮结果功能
2019/09/10 Javascript
JS typeof fn === 'function' &amp;&amp; fn()详解
2020/08/22 Javascript
python使用calendar输出指定年份全年日历的方法
2015/04/04 Python
在Python中操作时间之tzset()方法的使用教程
2015/05/22 Python
python3下实现搜狗AI API的代码示例
2018/04/10 Python
Python GUI Tkinter简单实现个性签名设计
2018/06/19 Python
python 的 openpyxl模块 读取 Excel文件的方法
2019/09/09 Python
分享一个pycharm专业版安装的永久使用方法
2019/09/24 Python
python 爬虫基本使用——统计杭电oj题目正确率并排序
2020/10/26 Python
Python爬虫之Selenium设置元素等待的方法
2020/12/04 Python
FORZIERI澳大利亚站:全球顶级奢华配饰精品店
2016/12/31 全球购物
Farfetch澳大利亚官网:Farfetch Australia
2020/04/26 全球购物
在购买印度民族服饰:Soch
2020/09/15 全球购物
Puccini乌克兰:购买行李箱、女士手袋网上商店
2020/08/06 全球购物
可以使用抽象函数重写基类中的虚函数吗
2013/06/02 面试题
人力资源部副职的竞聘演讲稿
2014/01/07 职场文书
中等生评语大全
2014/05/04 职场文书
知识改变命运演讲稿
2014/05/21 职场文书
运动会演讲稿300字
2014/08/25 职场文书
食堂采购员岗位职责
2015/04/03 职场文书
Python使用DFA算法过滤内容敏感词
2022/04/22 Python