0
#!/usr/bin/env python
#coding=utf-8
import sys,os,threading
import Queue


keyword = sys.argv[1]
path = sys.argv[2]


class keywordMatch(threading.Thread):
    def __init__(self,queue):
        threading.Thread.__init__(self)
        self.queue = queue
    def run(self):
        while True:
            line = self.queue.get()
            if keyword in line:
                print line

            queue.task_done()
def main():
    concurrent = 100 # Number of threads
    queue = Queue.Queue()

    for i in range(concurrent):
        t = keywordMatch(True)
        t.setDaemon(True)
        t.start()

    allfiles = os.listdir(path)
    for files in allfiles:
        pathfile = os.path.join(path,files)
        fp = open(pathfile)
        lines = fp.readlines()
        for line in lines:
            queue.put(line.strip())
    queue.join()


if __name__ == '__main__':
    main()

このプログラムは、ディレクトリ内のキーワードを検索するためのものですが、エラーが発生します:

Exception in thread Thread-100:
Traceback (most recent call last):
  File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 551, in __bootstrap_inner
    self.run()
  File "du.py", line 17, in run
    line = self.queue.get()
AttributeError: 'bool' object has no attribute 'get'

どうすればエラーを取り除くことができますか?

4

2 に答える 2

1

でスレッドをインスタンス化してt = keywordMatch(True)から、__init__この引数を取り、それを として保存しているself.queueので、当然self.queuebool になります。そこにQueueインスタンスが必要な場合は、それを渡す必要があります。

于 2013-10-20T12:18:23.453 に答える
1

あなたが書いたmain()

t = keywordMatch(True)

keywordMatchクラスはこれを__init__行います:

def __init__(self,queue):
    self.queue = queue

だから今self.queueですTrue!後で実行しようとするとself.queue.get、キューではないため失敗します。

于 2013-10-20T12:18:29.440 に答える