FashionMNIST / watch.py
rufimelo's picture
initial commit
a6b3107
import os
import subprocess
import sys
import time
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
class Watcher:
DIRECTORY_TO_WATCH = os.path.dirname(os.path.abspath(__file__))
def __init__(self, script_name):
self.script_name = script_name
self.observer = Observer()
def run(self):
event_handler = Handler(self.script_name)
self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
self.observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
self.observer.stop()
self.observer.join()
class Handler(FileSystemEventHandler):
def __init__(self, script_name):
self.script_name = script_name
self.process = subprocess.Popen([sys.executable, self.script_name])
def on_any_event(self, event):
if event.event_type == "modified" and event.src_path.endswith(".py"):
print(f"{event.src_path} changed. Restarting script...")
self.process.terminate()
self.process = subprocess.Popen([sys.executable, self.script_name])
if __name__ == "__main__":
# Replace 'app.py' with the name of your main Python script
w = Watcher("app.py")
w.run()