Spaces:
Sleeping
Sleeping
File size: 1,314 Bytes
a6b3107 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
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()
|