|
1
|
|
|
import yaml,threading,os,time |
|
2
|
|
|
import shelve |
|
3
|
|
|
|
|
4
|
|
|
MULTITHREADING = True |
|
5
|
|
|
lock = threading.Lock() |
|
6
|
|
|
|
|
7
|
|
|
class SingletonDecorator: |
|
8
|
|
|
def __init__(self,klass): |
|
9
|
|
|
self.klass = klass |
|
10
|
|
|
self.instance = None |
|
11
|
|
|
def __call__(self,*args,**kwds): |
|
12
|
|
|
if self.instance == None: |
|
13
|
|
|
self.instance = self.klass(*args,**kwds) |
|
14
|
|
|
return self.instance |
|
15
|
|
|
|
|
16
|
|
|
def yaml_load(filename): |
|
17
|
|
|
try: |
|
18
|
|
|
with open(filename+".old", "r") as file: |
|
19
|
|
|
res = yaml.load(file) |
|
20
|
|
|
return res |
|
21
|
|
|
except FileNotFoundError: |
|
22
|
|
|
try: |
|
23
|
|
|
with open(filename, "r") as file: |
|
24
|
|
|
res = yaml.load(file) |
|
25
|
|
|
return res |
|
26
|
|
|
except FileNotFoundError: |
|
27
|
|
|
return None |
|
28
|
|
|
|
|
29
|
|
|
def yaml_write(content,filename): |
|
30
|
|
|
rename = True |
|
31
|
|
|
try: |
|
32
|
|
|
os.rename(filename,filename+".old") |
|
33
|
|
|
except FileNotFoundError: |
|
34
|
|
|
rename = False |
|
35
|
|
|
try: |
|
36
|
|
|
with open(filename, "w+") as file: |
|
37
|
|
|
yaml.dump(content, file) |
|
38
|
|
|
except IOError: |
|
39
|
|
|
if rename: |
|
40
|
|
|
os.rename(filename+".old",filename) |
|
41
|
|
|
else: |
|
42
|
|
|
if rename: |
|
43
|
|
|
os.remove(filename+".old") |
|
44
|
|
|
print("finished") |
|
45
|
|
|
|
|
46
|
|
|
@SingletonDecorator |
|
47
|
|
|
class PersistableStack(object): |
|
48
|
|
|
def __init__(self, filename, multithreading=True): |
|
49
|
|
|
self.filename = filename |
|
50
|
|
|
self.thread = None |
|
51
|
|
|
self.values = None |
|
52
|
|
|
self.multithreading = multithreading |
|
53
|
|
|
|
|
54
|
|
|
def getValues(self): |
|
55
|
|
|
res = yaml_load(self.filename) |
|
56
|
|
|
if res is not None: |
|
57
|
|
|
self.values = res |
|
58
|
|
|
else: |
|
59
|
|
|
self.values = [] |
|
60
|
|
|
|
|
61
|
|
|
def push(self,element): |
|
62
|
|
|
if not self.values: |
|
63
|
|
|
self.getValues() |
|
64
|
|
|
self.values.append(element) |
|
65
|
|
|
self.persist(yaml_write,self.values,self.filename) |
|
66
|
|
|
|
|
67
|
|
|
def pop(self): |
|
68
|
|
|
if not self.values: |
|
69
|
|
|
self.getValues() |
|
70
|
|
|
res = self.values.pop() |
|
71
|
|
|
self.persist(yaml_write,self.values,self.filename) |
|
72
|
|
|
return res |
|
73
|
|
|
|
|
74
|
|
|
def persist(self,func,*args): |
|
75
|
|
|
if self.multithreading: |
|
76
|
|
|
with lock: |
|
77
|
|
|
self.thread = threading.Thread(target=func, args=args) |
|
78
|
|
|
self.thread.daemon = True |
|
79
|
|
|
self.thread.start() |
|
80
|
|
|
else: |
|
81
|
|
|
func(*args) |
|
82
|
|
|
|
|
83
|
|
|
@property |
|
84
|
|
|
def count(self): |
|
85
|
|
|
return len(self.values) |
|
86
|
|
|
|
|
87
|
|
|
|
|
88
|
|
|
if __name__ == "__main__": |
|
89
|
|
|
s = PersistableStack("bla") |
|
90
|
|
|
s.pop() |
|
91
|
|
|
print(s.values) |
|
92
|
|
|
|