2017-11-19 02:17:31 -05:00
|
|
|
class FileLockBase(object):
|
|
|
|
def __init__(self, fd):
|
|
|
|
if hasattr(fd, 'fileno') and callable(fd.fileno):
|
|
|
|
self.fd = fd.fileno()
|
|
|
|
else:
|
|
|
|
self.fd = fd
|
|
|
|
|
|
|
|
def acquire(self, blocking=True):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def release(self):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
self.acquire()
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
self.release()
|
|
|
|
|
2017-11-18 20:54:25 -05:00
|
|
|
|
|
|
|
try:
|
|
|
|
import msvcrt
|
|
|
|
except ImportError:
|
2017-11-19 02:17:31 -05:00
|
|
|
import fcntl
|
|
|
|
import os
|
2017-11-18 20:54:25 -05:00
|
|
|
|
2017-11-19 02:17:31 -05:00
|
|
|
class FileLock(FileLockBase):
|
2017-11-18 20:54:25 -05:00
|
|
|
def acquire(self, blocking=True):
|
2017-11-19 02:17:31 -05:00
|
|
|
fcntl.flock(self.fd, fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB))
|
2017-11-18 20:54:25 -05:00
|
|
|
|
|
|
|
def release(self):
|
2017-11-19 02:17:31 -05:00
|
|
|
fcntl.flock(self.fd, fcntl.LOCK_UN)
|
|
|
|
else:
|
|
|
|
class FileLock(FileLockBase):
|
|
|
|
def acquire(self, blocking=True):
|
2017-11-19 02:55:51 -05:00
|
|
|
msvcrt.locking(self.fd, (msvcrt.LK_NBLCK, msvcrt.LK_LOCK)[blocking], 2147483647)
|
2017-11-18 20:54:25 -05:00
|
|
|
|
2017-11-19 02:17:31 -05:00
|
|
|
def release(self):
|
2017-11-19 02:55:51 -05:00
|
|
|
msvcrt.locking(self.fd, msvcrt.LK_UNLCK, 2147483647)
|