def lock_and_write_buffer(obj, fname, offset, size): """Write the contents of a buffer to disk at a given offset, and explicitly lock the region of the file whilst doing so. Parameters ---------- obj : buffer Data to write to disk. fname : string Filename to write. offset : integer Offset into the file to start writing at. size : integer Size of the region to write to (and lock). """ import os import os.fcntl as fcntl buf = buffer(obj) if len(buf) > size: raise Exception("Size doesn't match array length.") fd = os.open(fname, os.O_RDRW | os.O_CREAT) fcntl.lockf(fd, fcntl.LOCK_EX, size, offset, os.SEEK_SET) nb = os.write(fd, buf) if nb != len(buf): raise Exception("Something funny happened with the reading.") fcntl.lockf(fd, fcntl.LOCK_UN) os.close(fd)