我正在尝试创建一个监视目录以进行更改的程序。将文件添加到相关目录时,FileHandler(FileSystemEventHandler的子类)将文件路径添加到队列中。一个名为ConsumeQueue的独立进程将定期检查队列中的项目。如果找到一个项目,它将从队列中获取文件路径并将其打印到控制台。以下是该程序的源代码:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from Queue import Empty
from multiprocessing import Process, Queue
class FileHandler(FileSystemEventHandler):
def __init__(self, q):
super(FileHandler, self).__init__()
self.q = q
def on_modified(self, event):
if not event.is_directory and not 'thumbnail' in event.src_path:
print "Created: " + event.src_path
self.q.put(event.src_path)
print 'Added', event.src_path, 'to queue', 'Queue size is now', self.q.qsize()
class ConsumeQueue(Process):
def __init__(self, q):
super(ConsumeQueue, self).__init__()
print 'Initializing'
self.q = q
def run(self):
print 'Running'
while True:
try:
value = self.q.get(False)
print 'Removed', value, 'from queue', 'Queue size is now', self.q.qsize()
except Empty:
print 'Nothing to process'
time.sleep(3)
if __name__ == "__main__":
q = Queue()
path = 'C:\path'
event_handler = FileHandler(q)
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
consumer = ConsumeQueue(q)
consumer.start()
observer.join()
consumer.join()
问题在于,虽然观察者似乎在向队列添加项目,但消费者根本没有运行。我认为调用consumer.start()至少会让它运行起来。我的计划有什么问题?
编辑 - 修正了缩进。