Last active
April 24, 2021 08:41
-
-
Save eecsmap/a5938da449437b127e658b978a682500 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import mmap | |
import contextlib | |
def gen(filename, length=0, offset=0): | |
create = not os.path.isfile(filename) | |
mode = 'w+b' if create else 'r+b' | |
with open(filename, mode) as fileobj: | |
if create and length == 0: length = 1 | |
if length: | |
fileobj.seek(length + offset - 1) | |
fileobj.write(b'\x00') | |
fileobj.flush() | |
with mmap.mmap(fileobj.fileno(), | |
length=0, | |
access=mmap.ACCESS_WRITE, | |
#offset=offset | |
) as mmap_obj: | |
yield mmap_obj | |
@contextlib.contextmanager | |
def mio(filename, length=0, offset=0): | |
handle = gen(filename, length, offset) | |
yield next(handle) | |
if __name__ == '__main__': | |
with mio('test.dat') as io: | |
print(io[:]) | |
handle = gen('test.dat') | |
io = next(handle) | |
io[0] = 42 | |
# When handle goes out of scope, io is closed | |
# this is very useful in interactive mode |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment