Skip to content

Instantly share code, notes, and snippets.

@kukuruza
Created October 4, 2017 15:03
Show Gist options
  • Save kukuruza/38c13b288f865aaa3e2ee23f2dd97c82 to your computer and use it in GitHub Desktop.
Save kukuruza/38c13b288f865aaa3e2ee23f2dd97c82 to your computer and use it in GitHub Desktop.
A simple utility class to wait until a file in the filesystem has changed.
# Usage:
# watcher = UpdateWatcher(changing_file_path)
# while True:
# watcher.wait_for_update()
# # Do my stuff.
import os, os.path as op
import time
import logging
class UpdateWatcher():
''' Use this class to wait until a file is updated.
The thread is blocked while waiting.
'''
def __init__(self, filepath):
self.CallInterval = 0.05 # Wait sec after unsuccessful attempt.
self.filepath = filepath
self.filetime = 0
def wait_for_update(self):
oldfiletime = self.filetime
filetime = op.getmtime(self.filepath)
firsttry = time.time()
while filetime == oldfiletime:
logging.debug('File not changed after %.2f sec.' % (time.time() - firsttry))
time.sleep(self.CallInterval)
filetime = op.getmtime(self.filepath)
self.filetime = filetime
logging.info('Input file updated after %.2f sec.' % (time.time() - firsttry))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment