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 24 Python
python出现&quot;IndentationError: unexpected indent&quot;错误解决办法
Oct 15 Python
解决tensorflow测试模型时NotFoundError错误的问题
Jul 27 Python
解决pycharm安装后代码区不能编辑的问题
Oct 28 Python
利用Python库Scapy解析pcap文件的方法
Jul 23 Python
python装饰器原理与用法深入详解
Dec 19 Python
pycharm不以pytest方式运行,想要切换回普通模式运行的操作
Sep 01 Python
Python fileinput模块如何逐行读取多个文件
Oct 05 Python
PyQt 如何创建自定义QWidget
Mar 24 Python
pytorch中的model.eval()和BN层的使用
May 22 Python
Python使用OpenCV和K-Means聚类对毕业照进行图像分割
Jun 11 Python
PYTHON InceptionV3模型的复现详解
May 06 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
15种PHP Encoder的比较
2007/04/17 PHP
解析PHP 使用curl提交json格式数据
2013/06/29 PHP
TP5(thinkPHP5)框架使用ajax实现与后台数据交互的方法小结
2020/02/10 PHP
IE php关于强制下载文件的代码
2008/08/23 Javascript
Three.js源码阅读笔记(Object3D类)
2012/12/27 Javascript
jquery触发a标签跳转事件示例代码
2013/07/21 Javascript
JavaScript常用数组算法小结
2016/02/13 Javascript
JS图片左右无缝隙滚动的实现(兼容IE,Firefox 遵循W3C标准)
2016/09/23 Javascript
百度地图JavascriptApi Marker平滑移动及车头指向行径方向
2017/03/13 Javascript
Angular中自定义Debounce Click指令防止重复点击
2017/07/26 Javascript
深入浅出webpack教程系列_安装与基本打包用法和命令参数详解
2017/09/10 Javascript
浅谈VUE-CLI脚手架热更新太慢的原因和解决方法
2018/09/28 Javascript
JS数组去重的6种方法完整实例
2018/12/08 Javascript
vue中uni-app 实现小程序登录注册功能
2019/10/12 Javascript
vue 中固定导航栏的实例代码
2019/11/01 Javascript
如何基于JS截获动态代码
2019/12/25 Javascript
一看就会的vuex实现登录验证(附案例)
2020/01/09 Javascript
Nodejs文件上传、监听上传进度的代码
2020/03/27 NodeJs
javascript实现下拉菜单效果
2021/02/09 Javascript
Django卸载之后重新安装的方法
2017/03/15 Python
python DataFrame 取差集实例
2019/01/30 Python
python中的函数递归和迭代原理解析
2019/11/14 Python
css3 iphone玻璃透明气泡完美实现
2013/03/20 HTML / CSS
使用HTML5 Geolocation实现一个距离追踪器
2018/04/09 HTML / CSS
应届毕业生个人求职信范文
2014/01/29 职场文书
教师个人鉴定材料
2014/02/08 职场文书
办公室主任主任岗位责任制
2014/02/11 职场文书
《姥姥的剪纸》教学反思
2014/02/25 职场文书
大学学习计划书范文
2014/05/02 职场文书
房屋授权委托书范本
2014/10/07 职场文书
机关作风建设自查报告
2014/10/22 职场文书
2014年骨干教师工作总结
2014/12/19 职场文书
七年级语文教学反思
2016/03/03 职场文书
用Python实现屏幕截图详解
2022/01/22 Python
MySQL数据库事务的四大特性
2022/04/20 MySQL
python小型的音频操作库mp3Play
2022/04/24 Python