-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflock.py
More file actions
50 lines (36 loc) · 1.22 KB
/
flock.py
File metadata and controls
50 lines (36 loc) · 1.22 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
import fcntl
class LockedException (Exception):
pass
class flock (object):
__slots__ = [ "file", "shared", "locked", "block" ]
def lock (self, *, shared=None):
shared = self.shared if shared is None else shared
flg = fcntl.LOCK_SH if shared else fcntl.LOCK_EX
fcntl.flock(self.file, flg)
self.locked = True
def try_lock (self, *, shared=None, throw=False):
shared = self.shared if shared is None else shared
flg = fcntl.LOCK_SH if shared else fcntl.LOCK_EX
try:
fcntl.flock(self.file, flg | fcntl.LOCK_NB)
self.locked = True
except OSError:
if throw:
raise LockedException
return False
return True
def unlock (self):
if self.locked:
fcntl.flock(self.file, fcntl.LOCK_UN)
self.locked = False
def __init__ (self, file, shared=False, block=True):
self.file = file
self.shared = shared
self.block = block
self.locked = False
def __del__ (self):
self.unlock()
def __enter__ (self, *_):
self.lock() if self.block else self.try_lock(throw=True)
def __exit__ (self, *_):
self.unlock()