【问题标题】:How to watch directory for file modifications如何监视目录以进行文件修改
【发布时间】:2012-05-13 03:01:05
【问题描述】:

我在 Mac 上。我一直在使用 Launchd 的 WatchPaths 指令来监视目录中的文件更改。我的脚本仅在从监视目录中添加或删除文件时触发。

但是,修改文件时脚本不会触发..

基本上,我正在尝试创建一个 DIY Dropbox 来同步我的站点文件夹。

有没有办法通过 launchd、bash 或 python 来做到这一点?

我认为linux有类似inotify的东西,但我不知道mac的解决方案。

【问题讨论】:

  • 理想情况下,我不想每 n 秒轮询一次更改...
  • 我知道的唯一解决方案是轮询。可以在此处找到我建议的方法示例:github.com/jessemiller/HamlPy/blob/… -- 我很想看看是否有人可以提供替代方法!
  • MacOS 支持 FreeBSD 风格的kqueue,在各方面与inotify 相似。如何真正让它工作,我不知道。 :-)
  • github.com/mynyml/watchr 是 Ruby 世界中这类事情的事实标准。对于 OS X,它依赖于 github.com/sandro/ruby-fsevent,这是一个暴露 OS X FSEvent API 的 Ruby 扩展。在 PyPI 上的搜索显示了一个 Python 等效项:pypi.python.org/pypi/MacFSEvents/0.2.1——也许这可能是要走的路?
  • 也许Watchdog 会做你想做的事?

标签: python macos bash launchd


【解决方案1】:

我尝试解决这个问题,使用MacFSEvents 包(available on PyPI,也是):

import os

from fsevents import Observer, Stream


def callback(file_event):
    print file_event.name # the path of the modified file


def main():
    observer = Observer()
    observe_path = os.getcwd() # just for this example
    stream = Stream(callback, observe_path, file_events=True)
    observer.start()
    observer.schedule(stream)


if __name__ == '__main__':
    main()

这将在任何时候创建、修改或删除文件时调用callback(您可以使用file_event.mask 的值检查发生了哪个事件)。

请注意,您可能希望在主线程之外的线程上进行观察(上述程序拒绝退出,即使在 KeyboardInterrupt 上也是如此)。有关 API 的更多信息可以在 MacFSEvents README 中找到。希望这会有所帮助!

【讨论】:

  • 这完全有帮助!不过,我对线程不熟悉.. 有什么可以了解更多或观察不同线程的指针吗?
  • JoeFish 推荐Watchdog,也许这会照顾到细节?否则,请查看these articles
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-02
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 2010-09-11
相关资源
最近更新 更多