From ae4615281f909f68d8cdd2e54e26d62aa46d250b Mon Sep 17 00:00:00 2001 From: Sebastien Bourdeauducq Date: Sun, 24 May 2015 21:26:15 +0800 Subject: [PATCH] pyon/store_file: replace previous file atomically --- artiq/protocols/pyon.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/artiq/protocols/pyon.py b/artiq/protocols/pyon.py index df7a0fa0c..320c691bf 100644 --- a/artiq/protocols/pyon.py +++ b/artiq/protocols/pyon.py @@ -20,6 +20,8 @@ function call syntax to mark special data types. import base64 from fractions import Fraction +import os +import tempfile import numpy @@ -158,18 +160,17 @@ def decode(s): def store_file(filename, x): - """Encodes a Python object and writes it to the specified file. - - """ + """Encodes a Python object and writes it to the specified file.""" contents = encode(x, True) - with open(filename, "w") as f: + directory = os.path.abspath(os.path.dirname(filename)) + with tempfile.NamedTemporaryFile("w", dir=directory, delete=False) as f: f.write(contents) f.write("\n") + tmpname = f.name + os.replace(tmpname, filename) def load_file(filename): - """Parses the specified file and returns the decoded Python object. - - """ + """Parses the specified file and returns the decoded Python object.""" with open(filename, "r") as f: return decode(f.read())