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.queue会成为一个布尔值。如果你想在那里有一个Queue实例,你应该把它传入。

于 2013-10-20T12:18:23.453 回答
1

main()你写道:

t = keywordMatch(True)

keywordMatch班级这样__init__做:

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

所以现在self.queueTrue!后来,尝试做self.queue.get失败,因为它根本不是一个队列。

于 2013-10-20T12:18:29.440 回答