How can I monitor a folder and execute an action when is open? (Eg: Python watchdog)

Viewed 545

I don't want to enable linux onedrive service as I've noticed it can be hard on my cpu, so I would rather run it on demand. That's why I'm trying to create a little script that would run onedrive sync one time only when I access OneDrive directory. Makes sense? I hope so.

I thought it would be easy but watchdog doesn't seem to have a way to monitor for that kind of event. Is there any other way I could do this ? Am I missing something ?

Here is watchdog documentation: https://python-watchdog.readthedocs.io/en/v0.10.2/quickstart.html#a-simple-example

import sys
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while observer.isAlive():
            observer.join(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

I'm running linux mint 19 in case it matters.

1 Answers

A good utility for executing actions when some files change is entr.

For example if you'd like to run some script upload_to_onedrive.sh every time a file changes in the directory onedrive you'd just ls ~/onedrive | entr ./upload_to_onedrive.sh

Related