
python殺死一個線程的方法
由于python線程沒有提供abort方法,所以我們需要自己想辦法解決此問題,面對這一問題,小編幫大家解決phthon殺死一個線程的方法
最近在項目中遇到這一需求:
我需要一個函數工作,比如遠程連接一個端口,遠程讀取文件等,但是我給的時間有限,比如,4秒鐘如果你還沒有讀取完成或者連接成功,我就不等了,很可能對方已經宕機或者拒絕了。這樣可以批量做一些事情而不需要一直等,浪費時間。
結合我的需求,我想到這種辦法:
1、在主進程執(zhí)行,調用一個進程執(zhí)行函數,然后主進程sleep,等時間到了,就kill 執(zhí)行函數的進程。
測試一個例子:
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]): 阻塞當前上下文環(huán)境的線程,直到調用此方法的線程終止或到達指定的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
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關鍵? 在循環(huán)神經網絡(RNN)家族中,長短期記憶網絡(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數據分析師報考條件詳解與準備指南? ? 在數據驅動決策的時代浪潮下,CDA 數據分析師認證愈發(fā)受到矚目,成為眾多有志投身數 ...
2025-07-11數據透視表中兩列相乘合計的實用指南? 在數據分析的日常工作中,數據透視表憑借其強大的數據匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實施重大更新。 此次更新旨在確保認 ...
2025-07-10BI 大數據分析師:連接數據與業(yè)務的價值轉化者? ? 在大數據與商業(yè)智能(Business Intelligence,簡稱 BI)深度融合的時代,BI ...
2025-07-10SQL 在預測分析中的應用:從數據查詢到趨勢預判? ? 在數據驅動決策的時代,預測分析作為挖掘數據潛在價值的核心手段,正被廣泛 ...
2025-07-10數據查詢結束后:分析師的收尾工作與價值深化? ? 在數據分析的全流程中,“query end”(查詢結束)并非工作的終點,而是將數 ...
2025-07-10CDA 數據分析師考試:從報考到取證的全攻略? 在數字經濟蓬勃發(fā)展的今天,數據分析師已成為各行業(yè)爭搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢性檢驗:捕捉數據背后的時間軌跡? 在數據分析的版圖中,單樣本趨勢性檢驗如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數據類型:時間維度的精準切片? ? 在數據的世界里,時間是最不可或缺的維度之一,而year_month數據類型就像一把精準 ...
2025-07-09CDA 備考干貨:Python 在數據分析中的核心應用與實戰(zhàn)技巧? ? 在 CDA 數據分析師認證考試中,Python 作為數據處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗:數據趨勢與突變分析的有力工具? ? ? 在數據分析的廣袤領域中,準確捕捉數據的趨勢變化以及識別 ...
2025-07-08備戰(zhàn) CDA 數據分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數據分析師認證作為國內權威的數據分析能力認證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應對策略? 長短期記憶網絡(LSTM)作為循環(huán)神經網絡(RNN)的一種變體,憑借獨特的門控機制,在 ...
2025-07-07統(tǒng)計學方法在市場調研數據中的深度應用? 市場調研是企業(yè)洞察市場動態(tài)、了解消費者需求的重要途徑,而統(tǒng)計學方法則是市場調研數 ...
2025-07-07CDA數據分析師證書考試全攻略? 在數字化浪潮席卷全球的當下,數據已成為企業(yè)決策、行業(yè)發(fā)展的核心驅動力,數據分析師也因此成為 ...
2025-07-07剖析 CDA 數據分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數據分析師考試作為衡量數據專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉日期:解鎖數據處理的關鍵技能? 在數據處理與分析工作中,數據格式的規(guī)范性是保證后續(xù)分析準確性的基礎 ...
2025-07-04CDA 數據分析師視角:從數據迷霧中探尋商業(yè)真相? 在數字化浪潮席卷全球的今天,數據已成為企業(yè)決策的核心驅動力,CDA(Certifie ...
2025-07-04CDA 數據分析師:開啟數據職業(yè)發(fā)展新征程? ? 在數據成為核心生產要素的今天,數據分析師的職業(yè)價值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03