-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalist.py
71 lines (53 loc) · 1.46 KB
/
alist.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import os
import pickle
import flock
def mkfile (*names):
for fname in map(os.path.realpath, names):
if not os.path.exists(fname):
os.makedirs(os.path.dirname(fname), exist_ok=True)
open(fname, "a").close()
def commit (file):
file.flush()
os.fsync(file.fileno())
def iterate_locked (file):
while True:
try:
data = pickle.load(file)
yield data
except EOFError:
break
def iterate (fname, shared=True):
with open(fname, "rb") as file:
with flock.flock(file, shared=shared):
yield from iterate_locked(file)
def read_locked (file):
result = []
while True:
try:
data = pickle.load(file)
result.append(data)
except EOFError:
break
return result
def read (fname, shared=True):
result = None
with open(fname, "rb") as file:
with flock.flock(file, shared=shared):
file.seek(0, os.SEEK_SET)
result = read_locked(file)
return result
def write_locked (file, *data, flush=True):
for value in data:
pickle.dump(value, file)
if flush:
commit(file)
return len(data)
def write (fname, *data, create=True):
written = 0
if create:
mkfile(fname)
with open(fname, "rb+") as file:
with flock.flock(file):
file.seek(0, os.SEEK_END)
written = write_locked(file, *data)
return written