Skip to content

Instantly share code, notes, and snippets.

@kskuhlman
Last active June 26, 2019 08:27
Show Gist options
  • Save kskuhlman/969c602ab4220e20380197563acd05ea to your computer and use it in GitHub Desktop.
Save kskuhlman/969c602ab4220e20380197563acd05ea to your computer and use it in GitHub Desktop.
#Cross-platform file watcher. Originally forked from:
#https://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes/49007649#49007649
import os
import sys
import time
import importlib
class Watcher(object):
running = True
refresh_delay_secs = 1
# Constructor
def __init__(self, watch_file, call_func_on_change=None, *args, **kwargs):
self._cached_stamp = 0
self.filename = watch_file
self.call_func_on_change = call_func_on_change
self.args = args
self.kwargs = kwargs
# Look for changes
def look(self):
stamp = os.stat(self.filename).st_mtime
if stamp != self._cached_stamp:
self._cached_stamp = stamp
# File has changed, so do something...
print('File changed')
if self.call_func_on_change is not None:
self.call_func_on_change(*self.args, **self.kwargs)
# Keep watching in a loop
def watch(self):
while self.running:
try:
# Look for changes
time.sleep(self.refresh_delay_secs)
self.look()
except KeyboardInterrupt:
print('\nDone')
break
except:
import traceback
print('Unhandled error: %s, %s' % (sys.exc_info()[1],sys.exc_info()[2]) )
print("Traceback:")
traceback.print_exc()
# Call this function each time a change happens
def custom_action(text):
# importlib is python >= 3.4 only
import ibuild
#try:
print("reloading")
importlib.reload(ibuild)
#except 'NameErrorx':
#print("initial load")
#import ibuild
#print("initial load complete")
watch_file = 'ibuild.py'
print('Starting watch on file %s' % watch_file)
# watcher = Watcher(watch_file) # simple
watcher = Watcher(watch_file, custom_action, text='yes, changed') # also call custom action function
watcher.watch() # start the watch going
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment