-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexclusive.py
33 lines (27 loc) · 843 Bytes
/
exclusive.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
'''
Use a file to denote whether a program is running.
'''
class Exclusive:
def __init__(self, filename) -> None:
self.filename = filename
def acquire(self):
try:
with open(self.filename, 'r+b') as f:
if f.read(1) == b'1':
raise Occupied
else: # Possible race condition. Too bad.
f.seek(0)
f.write(b'1')
f.flush()
except FileNotFoundError:
open(self.filename, 'wb').close()
self.acquire()
def release(self):
with open(self.filename, 'r+b') as f:
f.write(b'0')
def __enter__(self):
self.acquire()
def __exit__(self, *_):
self.release()
return False
class Occupied(Exception): pass