| 15 | |
| 16 | |
| 17 | def atomicWrite(dest, content, mode="wb"): |
| 18 | try: |
| 19 | with open(dest + "-tmpnew", mode) as f: |
| 20 | f.write(content) |
| 21 | f.flush() |
| 22 | os.fsync(f.fileno()) |
| 23 | if os.path.isfile(dest + "-tmpold"): # Previous incomplete write |
| 24 | os.rename(dest + "-tmpold", dest + "-tmpold-%s" % time.time()) |
| 25 | if os.path.isfile(dest): # Rename old file to -tmpold |
| 26 | os.rename(dest, dest + "-tmpold") |
| 27 | os.rename(dest + "-tmpnew", dest) |
| 28 | if os.path.isfile(dest + "-tmpold"): |
| 29 | os.unlink(dest + "-tmpold") # Remove old file |
| 30 | return True |
| 31 | except Exception as err: |
| 32 | from Debug import Debug |
| 33 | logging.error( |
| 34 | "File %s write failed: %s, (%s) reverting..." % |
| 35 | (dest, Debug.formatException(err), Debug.formatStack()) |
| 36 | ) |
| 37 | if os.path.isfile(dest + "-tmpold") and not os.path.isfile(dest): |
| 38 | os.rename(dest + "-tmpold", dest) |
| 39 | return False |
| 40 | |
| 41 | |
| 42 | def jsonDumps(data): |