Last active
August 1, 2020 20:27
-
-
Save 0ex-d/143616a44b0ef6488391e69aedd925f2 to your computer and use it in GitHub Desktop.
Python middle-ware to watch for changes in directory (Using watchdog)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Implements the basic http server and also | |
watch for directory changes, | |
requires pip install watchdog""" | |
import sys | |
import time | |
import logging | |
import http.server | |
import socketserver | |
from watchdog.observers import Observer | |
from watchdog.events import LoggingEventHandler | |
# set logging headers | |
logging.basicConfig(level=logging.INFO, | |
format='%(asctime)s - %(message)s', | |
datefmt='%Y-%m-%d %H:%M:%S') | |
# check if path to watch is given in std.io | |
# if not use the current working directory | |
path = sys.argv[1] if len(sys.argv) > 1 else '.' | |
event_handler = LoggingEventHandler() | |
observer = Observer() | |
observer.schedule(event_handler, path, recursive=True) | |
observer.start() | |
# set default port to 7000 | |
PORT = int(7000) | |
# keep server running until CMD+C or any terminate key is pressed | |
try: | |
while True: | |
time.sleep(1) | |
httpd.serve_forever() | |
except KeyboardInterrupt: | |
observer.stop() | |
observer.join() | |
# use default Python HTTP server | |
Handler = http.server.SimpleHTTPRequestHandler | |
httpd = socketserver.TCPServer(("", PORT), Handler) | |
print("Server started at port", PORT) | |
httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment