Skip to content

Instantly share code, notes, and snippets.

@JunaidQadirB
Created May 29, 2023 05:29
Show Gist options
  • Save JunaidQadirB/de9d722777a0976ad2274be11f0349d8 to your computer and use it in GitHub Desktop.
Save JunaidQadirB/de9d722777a0976ad2274be11f0349d8 to your computer and use it in GitHub Desktop.
Watch - A simple script to watch for changes in a python file and run it.
import argparse
import subprocess
import time
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
'''
Watch - A simple script to watch for changes in a python file and run it.
Usage: python watch.py [script_file]
if you don't specify a script_file, it will default to app.py
It requires watchdog to be installed
pip install watchdog
'''
class FileChangeHandler(FileSystemEventHandler):
def __init__(self, script_file):
self.script_file = script_file
def on_modified(self, event):
if not event.is_directory and event.src_path.endswith('.py'):
print(f"Changes detected in {event.src_path}")
subprocess.run(["python", self.script_file])
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("script_file", nargs='?', default="app.py", help="Python script file to watch")
args = parser.parse_args()
event_handler = FileChangeHandler(args.script_file)
observer = Observer()
observer.schedule(event_handler, path='.', recursive=True)
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