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+opencv轮廓检测代码解析
Jan 05 Python
Python实现按当前日期(年、月、日)创建多级目录的方法
Apr 26 Python
python之当你发现QTimer不能用时的解决方法
Jun 21 Python
Ranorex通过Python将报告发送到邮箱的方法
Jan 12 Python
Python爬虫库requests获取响应内容、响应状态码、响应头
Jan 25 Python
在Python中通过threshold创建mask方式
Feb 19 Python
解决jupyter notebook打不开无反应 浏览器未启动的问题
Apr 10 Python
解决Jupyter notebook更换主题工具栏被隐藏及添加目录生成插件问题
Apr 20 Python
python支持多继承吗
Jun 19 Python
python使用建议与技巧分享(一)
Aug 17 Python
Numpy实现卷积神经网络(CNN)的示例
Oct 09 Python
Python FuzzyWuzzy实现模糊匹配
Apr 28 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
全国FM电台频率大全 - 20 广西省
2020/03/11 无线电
全国FM电台频率大全 - 30 宁夏回族自治区
2020/03/11 无线电
php去除重复字的实现代码
2011/09/16 PHP
php实现根据词频生成tag云的方法
2015/04/17 PHP
PHP中通过trigger_error触发PHP错误示例
2015/06/23 PHP
PHP实现递归目录的5种方法
2016/10/27 PHP
PHP基于session.upload_progress 实现文件上传进度显示功能详解
2019/08/09 PHP
基于jQuery的为attr添加id title等效果的实现代码
2011/04/20 Javascript
Javascript引用指针使用介绍
2012/11/07 Javascript
javascript实现计时器的简单方法
2016/02/21 Javascript
浅谈jQuery中hide和fadeOut的区别 show和fadeIn的区别
2016/08/18 Javascript
javascript的document中的动态添加标签实现方法
2016/10/24 Javascript
ionic实现底部分享功能
2017/05/11 Javascript
Textarea输入字数限制实例(兼容iOS&amp;安卓)
2017/07/06 Javascript
EasyUI在Panel上动态添加LinkButton按钮
2017/08/11 Javascript
vue-cli初始化项目中使用less的方法
2018/08/09 Javascript
让 babel webpack vue 配置文件支持智能提示的方法
2019/06/22 Javascript
Python中的对象,方法,类,实例,函数用法分析
2015/01/15 Python
在Python中使用Neo4j数据库的教程
2015/04/16 Python
Python连接MySQL并使用fetchall()方法过滤特殊字符
2016/03/13 Python
python使用pil进行图像处理(等比例压缩、裁剪)实例代码
2017/12/11 Python
Python用imghdr模块识别图片格式实例解析
2018/01/11 Python
Python中extend和append的区别讲解
2019/01/24 Python
django组合搜索实现过程详解(附代码)
2019/08/06 Python
Python django框架开发发布会签到系统(web开发)
2020/02/12 Python
Python如何爬取b站热门视频并导入Excel
2020/08/10 Python
Anaconda详细安装步骤图文教程
2020/11/12 Python
市三好学生主要事迹
2014/01/28 职场文书
小学生考试获奖感言
2014/01/30 职场文书
党性心得体会
2014/09/03 职场文书
卖房授权委托书样本
2014/10/05 职场文书
离婚协议书格式范本
2016/03/18 职场文书
基于Python和openCV实现图像的全景拼接详细步骤
2021/10/05 Python
DIV CSS实现网页背景半透明效果
2021/12/06 HTML / CSS
十大公认最好看的动漫:《咒术回战》在榜,《钢之炼金术师》第一
2022/03/18 日漫
Redis keys命令的具体使用
2022/06/05 Redis