mirror of
https://github.com/Farama-Foundation/Gymnasium.git
synced 2025-08-27 16:57:10 +00:00
* Make sure that a callable is passed to start * Improve autoflushing for score calculation * Write stats and manifests using proper atomic_writes
30 lines
906 B
Python
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
|