Pyinotify / Watchdog 在一次编辑时触发两次修改事件



每次修改某个文件时,我都在尝试启动python脚本。准确地说,我在Raspberry Pi的串行端口上有一个设备,可以将数据写入文本文件(test.txt)。我已经尝试了两种工具 - 看门狗/Pyinotify。每次修改文件(触发事件看门狗:on_modified/Pyinotify:IN_MODIFY),它都会产生重复触发。我已经尝试了所有其他方法,甚至像某些人建议的那样IN_CLOSE_WRITE,但这根本不起作用。有人知道,如何在一次文件更新中只触发单个事件?

我使用Pyinotify的代码(一个经过编辑的教程文件):

import pyinotify,subprocess
def onChange(ev):
    cmd = ['/usr/bin/env', 'python', 'doThisFile.py', ev.pathname]
    subprocess.Popen(cmd).communicate()
wm = pyinotify.WatchManager()
wm.add_watch('/home/pi/test.txt', pyinotify.IN_MODIFY, onChange)
notifier = pyinotify.Notifier(wm)
notifier.loop()

或看门狗:

#!/usr/bin/python
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import subprocess
class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        subprocess.call("/home/pi/doThisFile.py")
        print("Code started")
if __name__ == "__main__":
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path='.', recursive=False)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

我在使用 pyinotify 时遇到了同样的问题。但是将IN_MODIFY改为IN_CLOSE_WRITE解决了这个问题。您可以从此答案中获取更多信息

这可能是因为用于编辑源代码的文本编辑器。解决方案:计算 2 个事件之间的时间,例如,如果事件触发过于频繁,请从其中一个事件退出处理程序。

class SubEventHandler(FileSystemEventHandler):
    def __init__(self):
        self._time0 = self.getTime()
    def on_modified(self, event):
        time1 = self.getTime()
        if (time1 - self._time0) < 5:
            exit(0) # not sure it will exit properly

您获得的 2 个事件是:

  1. 文件已修改
  2. 目录已修改

如果您运行演示代码,然后在触摸正在监视的目录中的文件,您将看到以下输出:

2022-11-04 10:28:45 - Modified file: ./test
2022-11-04 10:28:45 - Modified directory: .

最新更新