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 第一步 hello world
Sep 25 Python
Python中os和shutil模块实用方法集锦
May 13 Python
python抓取网页中图片并保存到本地
Dec 01 Python
基于Python中numpy数组的合并实例讲解
Apr 04 Python
解决pip install的时候报错timed out的问题
Jun 12 Python
python3实现字符串的全排列的方法(无重复字符)
Jul 07 Python
python3.4控制用户输入与输出的方法
Oct 17 Python
使用Python获取网段IP个数以及地址清单的方法
Nov 01 Python
对Python获取屏幕截图的4种方法详解
Aug 27 Python
使用python执行shell脚本 并动态传参 及subprocess的使用详解
Mar 06 Python
PyQt5 界面显示无响应的实现
Mar 26 Python
python机器学习实现oneR算法(以鸢尾data为例)
Mar 03 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分页示例代码
2007/03/19 PHP
Dwz与thinkphp整合下的数据导出到Excel实例
2014/12/04 PHP
PHP实现获取客户端IP并获取IP信息
2015/03/17 PHP
php htmlentities()函数的定义和用法
2016/05/13 PHP
PHP与Java对比学习日期时间函数
2016/07/03 PHP
php单元测试phpunit入门实例教程
2017/11/17 PHP
详细解读php的命名空间(一)
2018/02/21 PHP
JQuery 获取和设置Select选项的代码
2010/02/07 Javascript
在图片上显示左右箭头类似翻页的代码
2013/03/04 Javascript
js判断生效时间不得大于失效时间的思路及代码
2013/04/23 Javascript
vue的props实现子组件随父组件一起变化
2016/10/27 Javascript
JS简单实现移动端日历功能示例
2016/12/28 Javascript
微信小程序中post方法与get方法的封装
2017/09/26 Javascript
使用vue-route 的 beforeEach 实现导航守卫(路由跳转前验证登录)功能
2018/03/22 Javascript
JavaScript实现动态添加、移除元素或属性的方法分析
2019/01/03 Javascript
vue v-for循环重复数据无法添加问题解决方法【加track-by='索引'】
2019/03/15 Javascript
nodejs实现聊天机器人功能
2019/09/19 NodeJs
js删除指定位置超链接中含有百度与360的标题
2021/01/06 Javascript
[43:18]NB vs Infamous 2019国际邀请赛淘汰赛 败者组 BO3 第一场 8.22
2019/09/05 DOTA
详解Python的Django框架中的模版相关知识
2015/07/15 Python
Python聊天室实例程序分享
2016/01/05 Python
利用Python中unittest实现简单的单元测试实例详解
2017/01/09 Python
Python实现类似比特币的加密货币区块链的创建与交易实例
2018/03/20 Python
python读取和保存视频文件
2018/04/16 Python
python分批定量读取文件内容,输出到不同文件中的方法
2018/12/08 Python
Python发展简史 Python来历
2019/05/14 Python
通过pycharm使用git的步骤(图文详解)
2019/06/13 Python
python使用Thread的setDaemon启动后台线程教程
2020/04/25 Python
python矩阵运算,转置,逆运算,共轭矩阵实例
2020/05/11 Python
python3.7添加dlib模块的方法
2020/07/01 Python
巴西图书和电子产品购物网站:Saraiva
2017/06/07 全球购物
法国票务网站:Ticketmaster法国
2018/07/09 全球购物
家长写给老师的建议书
2014/03/13 职场文书
优秀教师先进个人事迹材料
2014/08/31 职场文书
反邪教警示教育活动总结
2015/05/09 职场文书
Elasticsearch 聚合查询和排序
2022/04/19 Python