pibootctl.files

The pibootctl.files module contains the AtomicReplaceFile context manager, used to “safely” replace files by writing to a temporary file in the same directory, then moving the result over the target if no exception occurs within the block. The result is that external processes either see the “old” state of the file, or the “new” state, but nothing in between:

>>> from pathlib import Path
>>> from pibootctl.files import AtomicReplaceFile
>>> foo = Path('foo.txt')
>>> foo.write_text('foo')
>>> foo.read_text()
'foo'
>>> with AtomicReplaceFile(foo, encoding='ascii') as f:
...     f.write('bar')
...     raise Exception('something went wrong!')
...
3
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
Exception: something went wrong!
>>> foo.read_text()
'foo'
class pibootctl.files.AtomicReplaceFile(path, encoding=None)[source]

A context manager for atomically replacing a target file.

Uses tempfile.NamedTemporaryFile() to construct a temporary file in the same directory as the target file. The associated file-like object is returned as the context manager’s variable; you should write the content you wish to this object.

When the context manager exits, if no exception has occurred, the temporary file will be renamed over the target file atomically (and sensible permissions will be set, i.e. 0666 & umask). If an exception occurs during the context manager’s block, the temporary file will be deleted leaving the original target file unaffected and the exception will be re-raised.

Parameters:
  • path (str or pathlib.Path) – The full path and filename of the target file. This is expected to be an absolute path.
  • encoding (str) – If None (the default), the temporary file will be opened in binary mode. Otherwise, this specifies the encoding to use with text mode.