2013-05-27 60 views
1

如果我將其中一個url更改爲無效,則整個進程將停止,並且我無法使用ctrl + c退出窗體終端。所以我的問題是我應該如何處理異常在我的主線程的run方法,如果錯誤發生觸發它,並轉到下一個列表元素不會失敗全proccess:python線程異常導致在下面的代碼中停止進程

#!/usr/bin/env python 
import Queue 
import threading 
import urllib2 
import time 

hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com","http://apple.com"] 

queue = Queue.Queue() 

class ThreadUrl(threading.Thread): 
    """Threaded Url Grab""" 
    def __init__(self, queue): 
     threading.Thread.__init__(self) 
     self.queue = queue 

    def run(self): 
     while True: 
      #grabs host from queue 
      host = self.queue.get() 

      #grabs urls of hosts and prints first 1024 bytes of page 
      url = urllib2.urlopen(host) 
      print "connected" 

      #signals to queue job is done 
      self.queue.task_done() 


start = time.time() 
def main(): 

    #spawn a pool of threads, and pass them queue instance 
    for i in range(5): 
     t = ThreadUrl(queue) 
     t.setDaemon(True) 
     t.start() 


    #populate queue with data 
    for host in hosts: 
     queue.put(host) 

    #wait on the queue until everything has been processed 
    queue.join() 
main() 
print "Elapsed Time: %s" % (time.time() - start) 

感謝

+0

把一個try/catch塊放在那裏,並處理異常。 – ismail

回答

3

使用finally阻止線程始終發出信號,即使出現錯誤也是如此。

def run(self): 
    while True: 
     #grabs host from queue 
     host = self.queue.get() 

     #grabs urls of hosts and prints first 1024 bytes of page 
     try: 
      url = urllib2.urlopen(host) 
      print "connected" 
     except urllib2.URLError: 
      print "couldn't connect to %s" % host 

     finally: 
      #signals to queue job is done 
      self.queue.task_done()