【问题标题】:Pyinotify / Watchdog triggers a modify event twice on one editPyinotify / Watchdog 在一次编辑时触发两次修改事件
【发布时间】:2016-06-11 21:17:47
【问题描述】:

每次修改某个文件时,我都会尝试启动 python 脚本。准确地说,我在 Raspberry Pi 的串行端口上有一个设备,它将数据写入文本文件 (test.txt) 。我已经尝试了这两种工具 - Watchdog / Pinotify。每次修改文件(触发事件看门狗: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()

【问题讨论】:

标签: python watchdog pyinotify


【解决方案1】:

我在使用pyinotify 时遇到了同样的问题。但是将IN_MODIFY 更改为IN_CLOSE_WRITE 解决了这个问题。你可以从这个answer获得更多信息

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      • 2020-01-31
      • 1970-01-01
      • 2021-10-01
      • 2022-10-06
      相关资源
      最近更新 更多