Watch a file and keep a parsed copy in memory that’s updated on changes.

The contents of the file are re-loaded and parsed only when necessary.

For example, a JSON file like the following:

  "one": 1,
  "two": 2

might be watched and parsed like this:

>>> watcher = FileWatcher(path, parser=json.load)
>>> watcher.get_data() == {u"one": 1, u"two": 2}

The return value of get_data() would change whenever the underlying file changes.

class baseplate.file_watcher.FileWatcher(path, parser, timeout=None)

Watch a file and load its data when it changes.

  • path (str) – Full path to a file to watch.
  • parser (callable) – A callable that takes an open file object, parses or otherwise interprets the file, and returns whatever data is meaningful.
  • timeout (float) – How long, in seconds, to block instantiation waiting for the watched file to become available (defaults to not blocking).

Return the current contents of the file, parsed.

The watcher ensures that the file is re-loaded and parsed whenever its contents change. Parsing only occurs when necessary, not on each call to this method. This method returns whatever the most recent call to the parser returned.

Make sure to call this method each time you need data from the file rather than saving its results elsewhere. This ensures you always have the freshest data.


exception baseplate.file_watcher.WatchedFileNotAvailableError(path, inner)

Raised when the watched file could not be loaded.