Skip to content

Instantly share code, notes, and snippets.

@Ronald-TR
Created June 22, 2020 17:42
Show Gist options
  • Save Ronald-TR/215c6c3047113afde451c6cd8049cb05 to your computer and use it in GitHub Desktop.
Save Ronald-TR/215c6c3047113afde451c6cd8049cb05 to your computer and use it in GitHub Desktop.
Simple live reload for terminal applications, refresh the terminal everytime that the file changes.
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import sys
import os
import time
import subprocess as subp
FILENAME = sys.argv[1]
PROC = None
def start_terminal(filename):
return subp.Popen(
[f'python {filename}'], stdout=subp.PIPE, shell=True, close_fds=False
)
def restart_terminal(proc):
kill_terminal(proc)
return start_terminal(FILENAME)
def kill_terminal(proc):
proc.kill()
class WatchHandler(FileSystemEventHandler):
def on_modified(self, event):
if event.src_path == os.path.abspath(FILENAME):
restart_terminal(PROC)
PROC = start_terminal(FILENAME)
path = os.path.join(os.getcwd(), os.path.dirname(FILENAME))
event_handler = WatchHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
@Ronald-TR
Copy link
Author

Need watchdog: that you can have with pip install watchdog

Usage:

python live_terminal.py path/to/file.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment