Python监视程序问题-缺少事件
我正在使用Python监视程序监视Ubuntu上的一个文件夹。它可以处理1到2个文件,但当我通过命令Python监视程序问题-缺少事件,python,watchdog,Python,Watchdog,我正在使用Python监视程序监视Ubuntu上的一个文件夹。它可以处理1到2个文件,但当我通过命令mv*.xml dest_folder移动50个文件时,它只接收到2个事件,只处理了2个文件。下面是代码 def on_moved(self, event): try: logger.debug("on_moved event :" + str(event) ) self._validate_xml(event.dest_path) except E
mv*.xml dest_folder
移动50个文件时,它只接收到2个事件,只处理了2个文件。下面是代码
def on_moved(self, event):
try:
logger.debug("on_moved event :" + str(event) )
self._validate_xml(event.dest_path)
except Exception as ex:
logger.exception(ex)
如果我注释掉\u validate\u xml
函数,那么我将收到所有45个事件
有谁能告诉我看门狗到底发生了什么,以及解决这个问题的最佳方案是什么?我没有使用Python看门狗,但从通用实时系统的角度来看
- 使用
处理xml可能会很慢,并使您错过事件\u validate\u xml
- 事件=与中断类似,处理速度应尽可能快
队列
(消息将是事件.dest_路径
)交换您看到移动的路径。事件处理将像将消息放入队列一样简单,队列的使用者可以批量处理文件
简言之:
- 实例化
队列
processfork()
- 在移动的处理程序中,将消息放入队列
- 在分叉过程中,从队列中弹出消息并调用
\u validate\u xml
- 您可以选择并行地利用do验证xml文件
线程化
#!/usr/bin/env python
import time
from watchdog.observers import Observer, api
from watchdog.events import LoggingEventHandler, FileSystemEventHandler, FileMovedEvent
import logging
def counter_gen():
count = 0
while True:
count += 1
yield count
class XmlValidatorHandler(FileSystemEventHandler):
sleep_time = 0.1
COUNTER = counter_gen()
def on_moved(self, event):
if isinstance(event, FileMovedEvent):
print '%s - event %d; validate: %s' % (
type(self).__name__, self.COUNTER.next(), event.dest_path)
time.sleep(self.sleep_time)
class SlowXmlValidatorHandler(XmlValidatorHandler):
sleep_time = 2
COUNTER = counter_gen()
def get_observer(handler):
observer = Observer(timeout=0.5)
observer.event_queue.maxsize=10
observer.schedule(handler, path='.', recursive=True)
return observer
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
event_handler = LoggingEventHandler()
observer1 = get_observer(XmlValidatorHandler())
observer2 = get_observer(SlowXmlValidatorHandler())
observer1.start()
observer2.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer1.stop()
observer2.stop()
observer1.join()
observer2.join()
无法重现您的问题。一些建议:
- 检查队列
,如果您已经在那里有项目,并且它们没有得到及时处理,那么我的猜测是maxsize
开始,并且超时
丢失。在这种情况下,您可能需要调整大小事件
- 选中
,如果已配置,则可能需要调整该参数超时
也许一个更完整的片段可以帮助我们帮助您。您好,谢谢您的快速回复。在您刚才提供的代码中,我更改了一行
observer.schedule(handler,path='./mont',recursive=True)
并通过mv命令将45个文件放在mont文件夹中,两个处理程序只得到2个事件。下面是打印消息*XmlValidatorHandler-事件1;验证:/home/devtool/test/mont/invalid\u test\u invalid\u data\u type.xlsx slowxmlvalidateHandler-事件1;验证:/home/devtool/test/mont/invalid\u test\u invalid\u data\u type.xlsx XmlValidatorHandler-事件2;验证:/home/devtool/test/mont/valid\u test\u offers\u terms\u HDVOD\u SDEST.xlsx SlowXmlValidatorHandler-事件2;验证:/home/devtool/test/mont/valid\u test\u preview\u missing.xlsx*甚至将队列大小更改为100,然后也一样。很抱歉,即使是注释\u validate\u xml函数也只能接收2个事件。