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 相关文章推荐
Windows系统配置python脚本开机启动的3种方法分享
Mar 10 Python
python使用opencv读取图片的实例
Aug 17 Python
Python pyinotify日志监控系统处理日志的方法
Mar 08 Python
Python代码缩进和测试模块示例详解
May 07 Python
Python 分发包中添加额外文件的方法
Aug 16 Python
python3 map函数和filter函数详解
Aug 26 Python
Python使用selenium + headless chrome获取网页内容的方法示例
Oct 16 Python
Python实现随机生成任意数量车牌号
Jan 21 Python
哈工大自然语言处理工具箱之ltp在windows10下的安装使用教程
May 07 Python
pycharm 激活码及使用方式的详细教程
May 12 Python
tensorflow使用L2 regularization正则化修正overfitting过拟合方式
May 22 Python
Python中如何添加自定义模块
Jun 09 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 CI框架插入一条或多条sql记录示例
2014/07/29 PHP
PHP计算日期相差天数实例分析
2016/02/23 PHP
详解PHP匿名函数与注意事项
2016/03/29 PHP
PHP Swoole异步Redis客户端实现方法示例
2019/10/24 PHP
jQuery制作简洁的图片轮播效果
2015/04/03 Javascript
javascript实现页面刷新时自动清空表单并选中的方法
2015/07/18 Javascript
JS折半插入排序算法实例
2015/12/02 Javascript
js获取当前日期时间及其它日期操作汇总
2016/03/08 Javascript
JS实现一次性弹窗的方法【刷新后不弹出】
2016/12/26 Javascript
js实现固定宽高滑动轮播图效果
2017/01/13 Javascript
angular $watch 一个变量的变化(实例讲解)
2017/08/02 Javascript
canvas轨迹回放功能实现
2017/12/20 Javascript
python实现巡检系统(solaris)示例
2014/04/02 Python
Python线程详解
2015/06/24 Python
Python中super()函数简介及用法分享
2016/07/11 Python
网站渗透常用Python小脚本查询同ip网站
2017/05/08 Python
对python 操作solr索引数据的实例详解
2018/12/07 Python
Python设计模式之观察者模式原理与用法详解
2019/01/16 Python
PyQt5实现让QScrollArea支持鼠标拖动的操作方法
2019/06/19 Python
Python坐标线性插值应用实现
2019/11/13 Python
tornado+celery的简单使用详解
2019/12/21 Python
Django 404、500页面全局配置知识点详解
2020/03/10 Python
解决c++调用python中文乱码问题
2020/07/29 Python
html5视频播放_动力节点Java学院整理
2017/07/13 HTML / CSS
仿酷狗html5手机音乐播放器主要部分代码
2013/05/15 HTML / CSS
用canvas画心电图的示例代码
2018/09/10 HTML / CSS
全球性的在线时尚男装零售商:boohooMAN
2016/12/17 全球购物
美国高档百货Nordstrom的折扣店:Nordstrom Rack
2017/11/13 全球购物
印尼在线旅游门户网站:NusaTrip
2019/11/01 全球购物
c/c++某大公司的两道笔试题
2014/02/02 面试题
Linux机考试题
2015/10/16 面试题
便利店的创业计划书
2014/01/15 职场文书
八一慰问活动方案
2014/02/07 职场文书
社区娱乐活动方案
2014/08/21 职场文书
学生上课迟到检讨书
2015/01/01 职场文书
Python insert() / append() 用法 Leetcode实战演示
2021/03/31 Python