#!/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'
如何摆脱错误?
你用 t = keywordMatch(True)
实例化线程,然后在__init__
中你接受这个参数并将其保存为self.queue
- 所以自然self.queue
将是一个布尔值。如果您希望那里有一个Queue
实例,则应将其传入。
在main()
你写道:
t = keywordMatch(True)
keywordMatch
类的__init__
是这样做的:
def __init__(self,queue):
self.queue = queue
所以现在self.queue
True
!稍后,尝试执行self.queue.get
失败,因为它根本不是队列。