0

I would like run my python script once a file in a certain folder is modified. To do this, I chose Watchdog.

First, I created an own project folder on my local machine and created and activated a venv. The following python script is also in the same folder which gets monitored.

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import pandas as pd

def on_modified(event):
    print("modified")
    test()


def test():
    print("test")


if __name__ == "__main__":
    path = 'C:/Users/MyUser/Desktop/Watchdog_test'
    event_handler = FileSystemEventHandler()

    event_handler.on_modified = on_modified

    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()

    try:
        print("monitoring")
        while True:
            time.sleep(3)
    except KeyboardInterrupt:
        observer.stop()
        print("Done")
    observer.join()

This is a easy example code but it shows the issue I have. So the code basically works and once I modify a file in the folder, I get "modified" in the terminal. Unfortunately, this does not trigger the function test(). In my real code I do the same but then trigger another function with triggers each function, like:

def on_modified(event):
    print("modified")
    trigger_all_functions()

def trigger_all_functions():
    function1(...)
    ... = function2(...)

and so on

3
  • This works perfectly fine for me on Linux and watchdog==3.0.0. Commented Nov 10, 2023 at 11:11
  • (Tangentially, code you put in if __name__ == '__main__': should be trivial; the purpose of this boilerplate is to allow you to import the code, which you will not want to do anyway if the logic you need is not available via import. See also stackoverflow.com/a/69778466/874188) , Commented Nov 10, 2023 at 11:33
  • I tried again without using the main function as the py.file don't need to be imported from some other python file. Not it works! So solution is the same code besides the if name == 'main': Commented Nov 10, 2023 at 13:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.