From e8513240ea1d2c8987d09b8acb9a2454d27154a9 Mon Sep 17 00:00:00 2001 From: dadav <33197631+dadav@users.noreply.github.com> Date: Fri, 13 Dec 2019 19:42:04 +0100 Subject: [PATCH] add ensure_write --- pwnagotchi/utils.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/pwnagotchi/utils.py b/pwnagotchi/utils.py index 4d0ba90c..0f912c84 100644 --- a/pwnagotchi/utils.py +++ b/pwnagotchi/utils.py @@ -10,6 +10,8 @@ import yaml import json import shutil import gzip +import contextlib +import tempfile import pwnagotchi @@ -345,6 +347,17 @@ def extract_from_pcap(path, fields): return results +@contextlib.contextmanager +def ensure_write(filename, mode='w'): + path = os.path.dirname(filename) + fd, tmp = tempfile.mkstemp(dir=path) + + with os.fdopen(fd, mode) as f: + yield f + f.flush() + os.fsync(f.fileno()) + + os.replace(tmp, filename) class StatusFile(object): def __init__(self, path, data_format='raw'): @@ -378,7 +391,7 @@ class StatusFile(object): def update(self, data=None): self._updated = datetime.now() self.data = data - with open(self._path, 'w') as fp: + with ensure_write(self._path, 'w') as fp: if data is None: fp.write(str(self._updated))