Skip to content

Instantly share code, notes, and snippets.

@kipavy
Created August 29, 2024 15:22
Show Gist options
  • Select an option

  • Save kipavy/dd0f2f9d27fc0388cf4a3bf361903c92 to your computer and use it in GitHub Desktop.

Select an option

Save kipavy/dd0f2f9d27fc0388cf4a3bf361903c92 to your computer and use it in GitHub Desktop.
Restart fitspy.main whenever a change is detected.
import os
import sys
import time
import subprocess
from watchdog.observers.polling import PollingObserver
from watchdog.events import FileSystemEventHandler
class RestartHandler(FileSystemEventHandler):
def __init__(self, script):
self.script = script
self.process = None
print("Initializing RestartHandler...") # Debugging statement
self.restart_script()
def restart_script(self):
if self.process:
print("Terminating existing process...") # Debugging statement
self.process.terminate()
self.process.wait()
print("Starting new process...") # Debugging statement
self.process = subprocess.Popen([sys.executable, '-m', self.script])
def on_modified(self, event):
print(f"Detected change in: {event.src_path}") # Debugging statement
if event.src_path.endswith(".py"):
print(f"File changed: {event.src_path}. Restarting script...")
self.restart_script()
if __name__ == "__main__":
script_to_run = "fitspy.main" # Use the module name without the function
path_to_watch = os.path.abspath(os.path.join(os.path.dirname(__file__), 'fitspy', 'fitspy'))
print(f"Monitoring path: {path_to_watch}") # Debugging statement
event_handler = RestartHandler(script_to_run)
observer = PollingObserver()
observer.schedule(event_handler, path=path_to_watch, recursive=True)
print("Starting observer...") # Debugging statement
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment