国产99久久精品_欧美日本韩国一区二区_激情小说综合网_欧美一级二级视频_午夜av电影_日本久久精品视频

最新文章專題視頻專題問答1問答10問答100問答1000問答2000關(guān)鍵字專題1關(guān)鍵字專題50關(guān)鍵字專題500關(guān)鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關(guān)鍵字專題關(guān)鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
當(dāng)前位置: 首頁 - 科技 - 知識(shí)百科 - 正文

python殺死一個(gè)線程的方法

來源:懂視網(wǎng) 責(zé)編:小采 時(shí)間:2020-11-27 14:34:44
文檔

python殺死一個(gè)線程的方法

python殺死一個(gè)線程的方法:最近在項(xiàng)目中遇到這一需求: 我需要一個(gè)函數(shù)工作,比如遠(yuǎn)程連接一個(gè)端口,遠(yuǎn)程讀取文件等,但是我給的時(shí)間有限,比如,4秒鐘如果你還沒有讀取完成或者連接成功,我就不等了,很可能對(duì)方已經(jīng)宕機(jī)或者拒絕了。這樣可以批量做一些事情而不需要一直等,浪費(fèi)時(shí)間。
推薦度:
導(dǎo)讀python殺死一個(gè)線程的方法:最近在項(xiàng)目中遇到這一需求: 我需要一個(gè)函數(shù)工作,比如遠(yuǎn)程連接一個(gè)端口,遠(yuǎn)程讀取文件等,但是我給的時(shí)間有限,比如,4秒鐘如果你還沒有讀取完成或者連接成功,我就不等了,很可能對(duì)方已經(jīng)宕機(jī)或者拒絕了。這樣可以批量做一些事情而不需要一直等,浪費(fèi)時(shí)間。

最近在項(xiàng)目中遇到這一需求:

我需要一個(gè)函數(shù)工作,比如遠(yuǎn)程連接一個(gè)端口,遠(yuǎn)程讀取文件等,但是我給的時(shí)間有限,比如,4秒鐘如果你還沒有讀取完成或者連接成功,我就不等了,很可能對(duì)方已經(jīng)宕機(jī)或者拒絕了。這樣可以批量做一些事情而不需要一直等,浪費(fèi)時(shí)間。

結(jié)合我的需求,我想到這種辦法:

1、在主進(jìn)程執(zhí)行,調(diào)用一個(gè)進(jìn)程執(zhí)行函數(shù),然后主進(jìn)程sleep,等時(shí)間到了,就kill 執(zhí)行函數(shù)的進(jìn)程。

測試一個(gè)例子:

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()

經(jīng)過測試只定了4秒鐘。

經(jīng)過我的一番折騰,想到了join函數(shù),這個(gè)函數(shù)式用來等待一個(gè)線程結(jié)束的,如果這個(gè)函數(shù)沒有結(jié)束的話,那么,就會(huì)阻塞當(dāng)前運(yùn)行的程序。關(guān)鍵是,這個(gè)參數(shù)有一個(gè)可選參數(shù):join([timeout]): 阻塞當(dāng)前上下文環(huán)境的線程,直到調(diào)用此方法的線程終止或到達(dá)指定的timeout(可選參數(shù))。

不多說了貼下面代碼大家看下:

#!/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: 
 #//添加你要做的事情,如果成功了就設(shè)置一下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

試了一下,很不錯(cuò),只是在要kill的線程中如果有time.sleep()時(shí),好像工作不正常,沒有找出真正的原因是什么。已經(jīng)是很強(qiáng)大了。哈哈。

聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

文檔

python殺死一個(gè)線程的方法

python殺死一個(gè)線程的方法:最近在項(xiàng)目中遇到這一需求: 我需要一個(gè)函數(shù)工作,比如遠(yuǎn)程連接一個(gè)端口,遠(yuǎn)程讀取文件等,但是我給的時(shí)間有限,比如,4秒鐘如果你還沒有讀取完成或者連接成功,我就不等了,很可能對(duì)方已經(jīng)宕機(jī)或者拒絕了。這樣可以批量做一些事情而不需要一直等,浪費(fèi)時(shí)間。
推薦度:
標(biāo)簽: 殺死 方法 的方法
  • 熱門焦點(diǎn)

最新推薦

猜你喜歡

熱門推薦

專題
Top
主站蜘蛛池模板: 亚洲国产视频网 | 日韩精品a在线视频 | 精品免费国产一区二区女 | 欧美日韩啪啪 | 欧美日韩精品一区二区三区高清视频 | 视频一区二区三区欧美日韩 | 国产一级特黄高清免费下载 | 久久久无码精品亚洲日韩按摩 | 国产精品视频一区二区三区经 | 亚洲国产成人久久综合碰 | 久久婷婷色一区二区三区 | 在线观看视频一区 | 亚洲 欧美 日韩 小说 另类 | 在线观看黄a大片爽爽影院免费 | 一区二区三区91 | 亚洲综合日韩 | 亚洲一区二区三区中文字幕 | 国产91精品一区二区视色 | 日韩高清欧美 | 久久久高清国产999尤物 | 日韩色视频 | 黄色免费网站视频 | 欧美人与禽x0x0牲伦交 | 欧美高清老少配性啪啪 | 国内精品视频在线观看 | 国产亚洲精品成人婷婷久久小说 | 成人一级免费视频 | 亚洲三级在线 | 国产v片在线观看 | 亚洲精品在线第一页 | 国产国语一级a毛片高清视频 | 国产一级片免费看 | 精品欧美一区二区三区免费观看 | 日韩欧美一区二区三区不卡在线 | 国产精品日本 | 日本在线不卡一区二区 | 国产a自拍 | 国产精品成人一区二区 | 91久久国产口精品久久久久 | 国产一二三区视频 | 真人一级一级毛片免费观看 |