热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

python杀死一个线程的方法

由于python线程没有提供abort方法,所以我们需要自己想办法解决此问题,面对这一问题,小编帮大家解决phthon杀死一个线程的方法,需要的朋友一起来学习吧
最近在项目中遇到这一需求:

我需要一个函数工作,比如远程连接一个端口,远程读取文件等,但是我给的时间有限,比如,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:   
      #//添加你要做的事情,如果成功了就设置一下self.thread_stop变量。 
[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高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • 学习SLAM的女生,很酷
    本文介绍了学习SLAM的女生的故事,她们选择SLAM作为研究方向,面临各种学习挑战,但坚持不懈,最终获得成功。文章鼓励未来想走科研道路的女生勇敢追求自己的梦想,同时提到了一位正在英国攻读硕士学位的女生与SLAM结缘的经历。 ... [详细]
  • 本文是一位90后程序员分享的职业发展经验,从年薪3w到30w的薪资增长过程。文章回顾了自己的青春时光,包括与朋友一起玩DOTA的回忆,并附上了一段纪念DOTA青春的视频链接。作者还提到了一些与程序员相关的名词和团队,如Pis、蛛丝马迹、B神、LGD、EHOME等。通过分享自己的经验,作者希望能够给其他程序员提供一些职业发展的思路和启示。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • Python字典推导式及循环列表生成字典方法
    本文介绍了Python中使用字典推导式和循环列表生成字典的方法,包括通过循环列表生成相应的字典,并给出了执行结果。详细讲解了代码实现过程。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • 本文介绍了使用Python根据字典中的值进行排序的方法,并给出了实验结果。通过将字典转化为记录项,可以按照字典中的值进行排序操作。实验结果显示,按照值进行排序后的记录项为[('b', 2), ('a', 3)]。 ... [详细]
  • Python如何调用类里面的方法
    本文介绍了在Python中调用同一个类中的方法需要加上self参数,并且规范写法要求每个函数的第一个参数都为self。同时还介绍了如何调用另一个类中的方法。详细内容请阅读剩余部分。 ... [详细]
  • Python语法上的区别及注意事项
    本文介绍了Python2x和Python3x在语法上的区别,包括print语句的变化、除法运算结果的不同、raw_input函数的替代、class写法的变化等。同时还介绍了Python脚本的解释程序的指定方法,以及在不同版本的Python中如何执行脚本。对于想要学习Python的人来说,本文提供了一些注意事项和技巧。 ... [详细]
  • 本文介绍了在Win10上安装WinPythonHadoop的详细步骤,包括安装Python环境、安装JDK8、安装pyspark、安装Hadoop和Spark、设置环境变量、下载winutils.exe等。同时提醒注意Hadoop版本与pyspark版本的一致性,并建议重启电脑以确保安装成功。 ... [详细]
  • 本文介绍了如何使用Python正则表达式匹配MATLAB的函数语法,包括多行匹配和跨行签名的处理方法。同时,作者还分享了自己遇到的问题和解决方案。 ... [详细]
  • 本文介绍了Python版Protobuf的安装和使用方法,包括版本选择、编译配置、示例代码等内容。通过学习本教程,您将了解如何在Python中使用Protobuf进行数据序列化和反序列化操作,以及相关的注意事项和技巧。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • 去掉空格的方法——Python工程师招聘标准与实践
    本文介绍了去掉空格的方法,并结合2019独角兽企业招聘Python工程师的标准与实践进行讨论。同时提供了一个转载链接,链接内容为更多相关信息。 ... [详细]
author-avatar
荷塘一只嫩藕
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有