2013-10-05 176 views
0

我知道這個問題被問了很多時間,但我仍然想知道。python停止線程正在運行

def startMonitor(self,event):  
    selectedInterface = self.interfaces_cblist.GetValue() 
    Publisher().sendMessage(("test"),selectedInterface) 
    self.Close() 
    selectInterfaceStr = str(selectedInterface) 
    if len(selectedInterface) == 0: 
     noSelect_error = wx.MessageDialog(None,"Please select an interface","",wx.OK|wx.ICON_ERROR) 
     noSelect_error.ShowModal() 
    else:  
     monitorStarted = wx.MessageDialog(None,"Monitor on %s started"%selectInterfaceStr,"",wx.OK|wx.ICON_ERROR) 
     monitorStarted.ShowModal() 
     self.monitorInterface_button.Disable() 
     thread.start_new_thread(self.camtableDetection,(selectInterfaceStr,)) 
     thread.start_new_thread(self.dhcpexhaustion,(selectInterfaceStr,)) 

我該如何停止穿線?

+1

這可能會有幫助:http://eli.thegreenplace.net/2011/12/27/python-threads-communication-and-stopping/ –

回答

0

您可以使用停止方法分配變量,例如self.abort。比在線程函數中,你應該定期檢查這個變量並停止函數(返回或類似的東西)。以下是一個使用此技術停止線程的示例類。

class PymineLogger: 
    def __init__(self): 
     self.file = open('server.log', 'a') 
     self.abort = False 
     self.log_queue = Queue.Queue() 
     threading.Thread(target=self.process_queue, args=()).start() 

    def error(self, i): 
     line = u'[%s] [ERROR] %s' % (str(time.time()), i) 
     self.log_queue.put(line) 

    def info(self, i): 
     line = u'[%s] [INFO] %s' % (str(time.time()), i) 
     self.log_queue.put(line) 

    def process_queue(self): 
     while not self.abort: 
      try: 
       log_line = self.log_queue.get(timeout=1) 
       print log_line 
       self.file.write("%s\n" % log_line) 
       self.file.flush() 
      except Queue.Empty: 
       pass 

    def stop(self): 
     self.abort = True 

停止方法分配可變self.abort,其被定期由線程檢查。

類來源:pymine2項目

+0

你知道我怎麼可以用wxpython來做呢?在哪裏觸發self.abort – ku1918

+0

@ ku1918我從來沒有使用過wxPython。所以我不知道。 – GKBRK