京公网安备 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)作为数据分布可视化的核心工具,凭借简洁的结构直观呈现数据的中位数、四分位数、异常值等关键信息,广泛应用 ...
2025-12-25在数据驱动决策的时代,基于历史数据进行精准预测已成为企业核心需求——无论是预测未来销售额、客户流失概率,还是产品需求趋势 ...
2025-12-25在数据驱动业务的实践中,CDA(Certified Data Analyst)数据分析师的核心工作,本质上是通过“指标”这一数据语言,解读业务现 ...
2025-12-25在金融行业的数字化转型进程中,SQL作为数据处理与分析的核心工具,贯穿于零售银行、证券交易、保险理赔、支付结算等全业务链条 ...
2025-12-24在数据分析领域,假设检验是验证“数据差异是否显著”的核心工具,而独立样本t检验与卡方检验则是其中最常用的两种方法。很多初 ...
2025-12-24在企业数字化转型的深水区,数据已成为核心生产要素,而“让数据可用、好用”则是挖掘数据价值的前提。对CDA(Certified Data An ...
2025-12-24数据分析师认证考试全面升级后,除了考试场次和报名时间,小伙伴们最关心的就是报名费了,报 ...
2025-12-23CDA中国官网是全国统一的数据分析师认证报名网站,由认证考试委员会与持证人会员、企业会员以及行业知名第三方机构共同合作,致 ...
2025-12-23在Power BI数据可视化分析中,矩阵是多维度数据汇总的核心工具,而“动态计算平均值”则是矩阵分析的高频需求——无论是按类别计 ...
2025-12-23在SQL数据分析场景中,“日期转期间”是高频核心需求——无论是按日、周、月、季度还是年度统计数据,都需要将原始的日期/时间字 ...
2025-12-23在数据驱动决策的浪潮中,CDA(Certified Data Analyst)数据分析师的核心价值,早已超越“整理数据、输出报表”的基础层面,转 ...
2025-12-23在使用Excel数据透视表进行数据分析时,我们常需要在透视表旁添加备注列,用于标注数据背景、异常说明、业务解读等关键信息。但 ...
2025-12-22在MySQL数据库的性能优化体系中,索引是提升查询效率的“核心武器”——一个合理的索引能将百万级数据的查询耗时从秒级压缩至毫 ...
2025-12-22在数据量爆炸式增长的数字化时代,企业数据呈现“来源杂、格式多、价值不均”的特点,不少CDA(Certified Data Analyst)数据分 ...
2025-12-22在企业数据化运营体系中,同比、环比分析是洞察业务趋势、评估运营效果的核心手段。同比(与上年同期对比)可消除季节性波动影响 ...
2025-12-19在数字化时代,用户已成为企业竞争的核心资产,而“理解用户”则是激活这一资产的关键。用户行为分析系统(User Behavior Analys ...
2025-12-19在数字化转型的深水区,企业对数据价值的挖掘不再局限于零散的分析项目,而是转向“体系化运营”——数据治理体系作为保障数据全 ...
2025-12-19在数据科学的工具箱中,析因分析(Factor Analysis, FA)、聚类分析(Clustering Analysis)与主成分分析(Principal Component ...
2025-12-18自2017年《Attention Is All You Need》一文问世以来,Transformer模型凭借自注意力机制的强大建模能力,在NLP、CV、语音等领域 ...
2025-12-18在CDA(Certified Data Analyst)数据分析师的时间序列分析工作中,常面临这样的困惑:某电商平台月度销售额增长20%,但增长是来 ...
2025-12-18