转自: http://www.jb51.net/article/71908.htm

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

最近在项目中遇到这一需求:

我需要一个函数工作,比如远程连接一个端口,远程读取文件等,但是我给的时间有限,比如,4秒钟如果你还没有读取完成或者连接成功,我就不等了,很可能对方已经宕机或者拒绝了。这样可以批量做一些事情而不需要一直等,浪费时间。

结合我的需求,我想到这种办法:

1、在主进程执行,调用一个进程执行函数,然后主进程sleep,等时间到了,就kill 执行函数的进程。

测试一个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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(可选参数)。

不多说了贴下面代码大家看下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/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方法,分享下面一段代码杀死线程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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)

使用例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> 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执行线程方法的更多相关文章

  1. Python进阶----线程基础,开启线程的方式(类和函数),线程VS进程,线程的方法,守护线程,详解互斥锁,递归锁,信号量

    Python进阶----线程基础,开启线程的方式(类和函数),线程VS进程,线程的方法,守护线程,详解互斥锁,递归锁,信号量 一丶线程的理论知识 什么是线程:    1.线程是一堆指令,是操作系统调度 ...

  2. jmeter 执行python脚本的方法 。(亲测ok)

    jmeter 执行python脚本   jmeter 可以通过Jython 执:行python代码 1.下载Jython jar包:http://www.jython.org/downloads.ht ...

  3. Python执行系统命令的方法 os.system(),os.popen(),commands

    os.popen():用python执行shell的命令,并且返回了结果,括号中是写shell命令 Python执行系统命令的方法: https://my.oschina.net/renwofei42 ...

  4. Python执行效率测试模块timei的使用方法与与常用Python用法的效率比较

    timeit模块用于测试一段代码的执行效率 1.Timer类 Timer 类: __init__(stmt="pass", setup="pass", time ...

  5. Python执行Linux系统命令方法

    Python执行Linux系统命令的4种方法 (1) os.system 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息 复制代码代码如下: system(command) -> ...

  6. python执行linux命令的两种方法

    python执行linux命令有两种方法: 在此以Linux常用的ls命令为例: 方法一:使用os模块 1 2 3 shell# python >> import os >> ...

  7. 提高python执行效率的方法

    python上手很容易,但是在使用过程中,怎么才能使效率变高呢? 下面说一下提高python执行效率的方法,这里只是说一点,python在引入模块过程中提高效率的方法. 例如: 1.我们要使用os模块 ...

  8. 转 Python执行系统命令的方法

    传送门 Python执行系统命令的方法 http://www.linux-field.com/?p=15 Python中执行系统命令常见方法有两种: 两者均需 import os (1) os.sys ...

  9. Python执行系统命令并获得输出的几种方法

    [root@a upfc]# ./ffmpeg-linux64-v3.3.1 -i a.mp3 ffmpeg version N-86111-ga441aa90e8-static http://joh ...

随机推荐

  1. 【BZOJ】3521: [Poi2014]Salad Bar

    题意 长度为\(n(1 \le n \le 1000000)\)的\(01\)字符串.找一个最长的连续子串\(S\),使得不管是从左往右还是从右往左取,都保证每时每刻已取出的\(1\)的个数不小于\( ...

  2. GridView,Repeater增加自动序号列

    有三种实现的方式, 第一种方式,直接在Aspx页面GridView模板列中.这种的缺点是到第二页分页时又重新开始了. <Columns> <asp:TemplateField Hea ...

  3. jQuery实现全选效果【转】

    这是一段用jquery实现全选的代码,主要思路如下: 1.所有的复选框都有单击事件,所有效果都是在单击事件下实现的 2.全选复选框所实现的功能与其他复选选项实现的功能不同,所有在单击事件内做一个判断, ...

  4. mysql刷日志的两个参数

    innodb_flush_log_at_trx_commit 0:每秒 ----log---disk1:事物提交 ---log ---disk2:事物提交---log 每秒 ---disk sync_ ...

  5. Intellij如何设置编译后自动重新加载class文件?

    前段时间突然发现Intellij不能自动重新加载类了,每次编译后都要重新启动项目,才能显示更新效果,后来网上查询Intellij下如何配置热部署,都说是要配置构件,然后在web容器的编辑页面选择upd ...

  6. linux内核分析作业4:使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用

    系统调用:库函数封装了系统调用,通过库函数和系统调用打交道 用户态:低级别执行状态,代码的掌控范围会受到限制. 内核态:高执行级别,代码可移植性特权指令,访问任意物理地址 为什么划分级别:如果全部特权 ...

  7. 一个简易的四则运算单元...(15.12.15 BUG更新)

    网上找的, 没有作者信息, 只能在这里感谢一下了, 支持标准写法的四则运算 --2015-12-15 修改了一个内存泄漏的BUG - Pop方法没有释放申请的内存 unit Base.Calculat ...

  8. Spring IoC容器初始化过程学习

    IoC容器是什么?IoC文英全称Inversion of Control,即控制反转,我么可以这么理解IoC容器: 把某些业务对象的的控制权交给一个平台或者框架来同一管理,这个同一管理的平台可以称为I ...

  9. 正则表达式中的exec和match方法的区别

    正则表达式中的exec和match方法的区别 字符串的正则方法有:match().replace().search().split() 正则对象的方法有:exec().test() 1.match m ...

  10. iOS10新特性

    1.Siri API 的开放自然是 iOS 10 SDK 中最激动人心也是亮眼的特性.Apple 加入了一套全新的框架 Intents.framework 来表示 Siri 获取并解析的结果. 在 i ...