Files
Gymnasium/gym/utils/atomic_write.py
Greg Brockman 9984589731 Improve score_from_local implementation (#66)
* Make sure that a callable is passed to start

* Improve autoflushing for score calculation

* Write stats and manifests using proper atomic_writes
2016-05-06 18:19:16 -07:00

30 lines
906 B
Python

# From http://stackoverflow.com/questions/2333872/atomic-writing-to-file-with-python
import os
from contextlib import contextmanager
@contextmanager
def atomic_write(filepath, binary=False, fsync=False):
""" Writeable file object that atomically updates a file (using a temporary file).
:param filepath: the file path to be opened
:param binary: whether to open the file in a binary mode instead of textual
:param fsync: whether to force write the file to disk
"""
tmppath = filepath + '~'
while os.path.isfile(tmppath):
tmppath += '~'
try:
with open(tmppath, 'wb' if binary else 'w') as file:
yield file
if fsync:
file.flush()
os.fsync(file.fileno())
os.rename(tmppath, filepath)
finally:
try:
os.remove(tmppath)
except (IOError, OSError):
pass