Search code examples
pythonmacosbashlaunchd

How to watch directory for file modifications


I'm on a mac. I've been using Launchd's WatchPaths directive to watch a directory for file changes. My script only triggers when a file is added or deleted from the watched directory.

However, the script does not trigger when a file is modified..

Essentially, I'm trying to create a DIY Dropbox for syncing my Sites folder.

Is there a way to do this via launchd, bash or python?

I think linux has something like inotify, but I am not aware of a solution for mac.


Solution

  • I tried my hand at the problem, using the MacFSEvents package (available on PyPI, too):

    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()
    

    This will call callback any time a file is created, modified, or deleted (you can check which event occurred using the value of file_event.mask).

    Note that you will probably want to observe on a thread outside of the main thread (the above program refuses to quit, even on KeyboardInterrupt). More information on the API can be found in the MacFSEvents README. Hope this helps!