2014-03-06 77 views
3

我的屏幕顯示<type 'exceptions.TypeError'>: 'NoneType' object is not callable當我運行下面這段代碼:Python的線程模塊錯誤:「NoneType」對象不是可調用

import threading 
import urllib2 
import Queue 
import time 

hosts = ["http://baidu.com", "http://yahoo.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 byte of page 
      url = urllib2.urlopen(host) 

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

start = time.time() 
def main(): 
    for i in range(2): 
     t = ThreadUrl(queue) 
     t.setDaemon(True) 
     t.start() 

     for host in hosts: 
      queue.put(host) 

    queue.join() 

main() 
print "Elapsed Time: %s" % (time.time() - start) 

這是錯誤的詳細信息:

Exception in thread Thread-3 (most likely raised during interpreter shutdown): 
Traceback (most recent call last): 
File "/usr/local/lib/python2.7/threading.py", line 808, in __bootstrap_inner 
File "url_thread.py", line 21, in run 
File "/usr/local/lib/python2.7/Queue.py", line 168, in get 
File "/usr/local/lib/python2.7/threading.py", line 332, in wait 
<type 'exceptions.TypeError'>: 'NoneType' object is not callable 

這有什麼錯我的代碼?非常感謝。

+0

使用'超(ThreadUrl,個體經營).__的init __()'比其他'threading.Thread .__的init __(個體經營)建議',看到http://stackoverflow.com/questions/576169/understanding-python -super-and-init-methods – shuiyu

+0

感謝您的評論。但它發生同樣的錯誤。我的系統上的 – changzhi

+0

(win 7 x64; python 2.7.1 32bit你的代碼工作正常 –

回答

1

這是一個python 2.7 bug - Shutdown exception in daemon thread。 你可以讓線程非deamon,並通過隊列傳遞一個標記來指示它們退出,然後將它們從主線程中加入。

import threading 
import urllib2 
import Queue 
import time 

hosts = ["http://baidu.com", "http://yahoo.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() 
      if host is None: 
       self.queue.task_done() 
       return 

      #grabs urls of hosts and prints first 1024 byte of page 
      url = urllib2.urlopen(host) 

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

start = time.time() 
def main(): 
    threads = [ThreadUrl(queue) for _ in range(2)] 
    map(lambda t: t.start() threads) 
    for i in range(2): 
     for host in hosts: 
      queue.put(host) 
    for t in threads: 
     queue.put(None) 
    queue.join() 
    map(lambda t: t.join() threads) 

main() 
print "Elapsed Time: %s" % (time.time() - start) 
相關問題