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.lib.file_watcher.FileWatcher(path, parser, timeout=None, binary=False, encoding=None, newline=None, backoff=None)[source]

Watch a file and load its data when it changes.

  • path (str) – Full path to a file to watch.
  • parser (Callable[[Io[AnyStr]], ~T]) – A callable that takes an open file object, parses or otherwise interprets the file, and returns whatever data is meaningful.
  • timeout (Optional[float]) – How long, in seconds, to block instantiation waiting for the watched file to become available (defaults to not blocking).
  • binary (bool) – Should the file be opened in binary mode. If True the file will be opened with the mode “rb”, otherwise it will be opened with the mode “r”. (defaults to “r”)
  • encoding (Optional[str]) – The name of the encoding used to decode the file. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. This is not supported if binary is set to True.
  • newline (Optional[str]) – Controls how universal newlines mode works (it only applies to text mode). It can be None, “”, “\n”, “\r”, and “\r\n”. This is not supported if binary is set to True.
  • backoff (Optional[float]) – retry backoff time for the file watcher. Defaults to None, which is mapped to DEFAULT_FILEWATCHER_BACKOFF.

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.

Return type:~T


exception baseplate.lib.file_watcher.WatchedFileNotAvailableError(path, inner)[source]

Raised when the watched file could not be loaded.