99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀python殺死一個線程的方法
python殺死一個線程的方法
2017-08-17
收藏

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

數據分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調用 initGeetest 進行初始化 // 參數1:配置參數 // 參數2:回調,回調的第一個參數驗證碼對象,之后可以使用它調用相應的接口 initGeetest({ // 以下 4 個配置參數為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產品形式,包括:float,popup width: "280px", https: true // 更多配置參數說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }