京公网安备 11010802034615号
经营许可证编号:京B2-20210330
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()时,好像工作不正常,没有找出真正的原因是什么。已经是很强大了。
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
在数据清洗、统计分析与数据质量检测工作中,箱型图(又称箱线图、Box Plot)是最直观、最高效的可视化分析工具之一。相较于柱状 ...
2026-05-25在大数据分析、数据清洗、质量管控、风险监测等领域,异常数据识别是保障数据质量、确保分析结论精准、规避业务决策失误的核心基 ...
2026-05-25 很多数据分析师精通Excel函数和透视表,但当被问到“数据从哪里来”“表和视图有什么区别”“数据库管理系统和SQL是什么关系 ...
2026-05-25数字化经营时代,企业的市场竞争早已从经验决策转向数据决策。门店营收、用户转化、产品销量、成本损耗、存量资产等所有经营行为 ...
2026-05-22在MySQL数据库日常运维、业务数据校验、数据迁移与数据清洗场景中,自增主键ID的连续性校验是一项基础且关键的工作。MySQL的Auto ...
2026-05-22 很多企业团队并非缺乏指标,而是陷入“指标失控”:仪表盘上堆满实时跳动的数据,却无法回答“当前瓶颈在哪、下一步该做什么 ...
2026-05-22【核心关键词】大数据、可视化、存储、架构、客户、离线、产品、同步、实时、数据仓库、数据分析、数据可视化、存储数据、离线 ...
2026-05-21在电商流量红利消退、公域获客成本持续走高的当下,存量用户深度挖掘已成为店铺增收增效的核心抓手。相较于付费投放获取的陌生新 ...
2026-05-21 很多数据分析师每天盯着几十个指标,但当被问到“这套指标要支撑什么业务目标”“指标之间是什么逻辑关系”“业务变化时如何 ...
2026-05-21在数据驱动决策的时代,数据质量直接决定分析结果的可靠性与准确性,而异常值作为数据清洗中的核心痛点,往往会扭曲分析结论、误 ...
2026-05-20 很多数据分析师每天盯着GMV、DAU、转化率,但当被问到“哪些指标在所有行业都适用”“哪些指标只对电商有意义”“二者如何搭 ...
2026-05-20Agent的能力边界,很大程度上取决于其掌握的Skill质量和数量。传统做法是靠人工编写和维护Skill,但这条路很快会遇到瓶颈。业务 ...
2026-05-20在统计分析中,方差分析(ANOVA)是一种常用的假设检验方法,核心用于分析“一个或多个自变量对单个因变量的影响”,广泛应用于 ...
2026-05-19 很多数据分析师每天盯着GMV、DAU、转化率,但当被问到“什么是指标”“指标和维度有什么区别”“如何定义指标值的计算规则和 ...
2026-05-19想高效备考 CDA 一级,拒绝盲目刷题、冗余学习?《CDA 一级教材知识手册》重磅来袭!以官方教材为核心,浓缩 13 章 103 个核心考 ...
2026-05-19在数据统计分析中,卡方检验是一种常用的非参数检验方法,核心用于判断两个或多个分类变量之间是否存在显著关联,广泛应用于市场 ...
2026-05-18在企业数字化转型的浪潮中,很多企业陷入了“技术堆砌”的误区——上线了ERP、CRM、BI等各类系统,积累了海量数据,却依然面临“ ...
2026-05-18小陈是某电商平台的数据分析师。老板交给他一个任务:“我们平台的注册用户已经突破1000万了,想了解一下用户的平均月消费金额。 ...
2026-05-18【专访摘要】本次CDA持证专访邀请到拥有丰富物流供应链数据分析经验的赖尧,他结合自身在京东、华莱士、兰格赛等企业的从业经历 ...
2026-05-15在数字化时代,企业的每一次业务优化、每一项技术迭代,都需要回答一个核心问题:这个动作到底能带来多少价值?是提升了用户转化 ...
2026-05-15