-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_lock.py
More file actions
68 lines (42 loc) · 1.28 KB
/
file_lock.py
File metadata and controls
68 lines (42 loc) · 1.28 KB
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
import fcntl
import os
class FileLock():
def __init__(self, path, *args, **kwargs):
self.path = path
self.file = None
self.is_locked = False
def __enter__(self, *args, **kwargs):
self.acquire()
return True
def __exit__(self, exc_type=None, exc_value=None, traceback=None):
self.release()
if exc_type != None:
return False
return True
def acquire(self):
self.file = open(self.path, 'w')
self._acquire()
self.is_locked = True
def release(self):
self.file.flush()
os.fsync(self.file.fileno() )
self._release()
self.is_locked = False
self.file.close()
self.file = None
def _acquire(self):
if self.file.writable():
fcntl.lockf(self.file, fcntl.LOCK_EX)
def _release(self):
if self.file.writable():
fcntl.lockf(self.file, fcntl.LOCK_UN)
def is_locked(self):
return self.is_locked
def acquire(self):
if self.file.writable():
fcntl.lockf(self.file, fcntl.LOCK_EX)
def release(self):
if self.file.writable():
fcntl.lockf(self.file, fcntl.LOCK_UN)
def is_locked(self):
return self.is_locked