Другие решения ссылаются на множество внешних кодовых баз. Если вы предпочитаете делать это самостоятельно, вот какой-то код для кросс-платформенного решения, в котором используются соответствующие инструменты блокировки файлов в системах Linux / DOS.
try:
# Posix based file locking (Linux, Ubuntu, MacOS, etc.)
import fcntl
def lock_file(f):
fcntl.lockf(f, fcntl.LOCK_EX)
def unlock_file(f): pass
except ModuleNotFoundError:
# Windows file locking
import msvcrt
def file_size(f):
return os.path.getsize( os.path.realpath(f.name) )
def lock_file(f):
msvcrt.locking(f.fileno(), msvcrt.LK_RLCK, file_size(f))
def unlock_file(f):
msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, file_size(f))
# Class for ensuring that all file operations are atomic, treat
# initialization like a standard call to 'open' that happens to be atomic
class AtomicOpen:
# Open the file with arguments provided by user. Then acquire
# a lock on that file object (WARNING: Advisory locking)
def __init__(self, path, *args, **kwargs):
# Open the file and acquire a lock on the file before operating
self.file = open(path,*args, **kwargs)
# Lock the opened file
lock_file(self.file)
# Return the opened file object (knowing a lock has been obtained)
def __enter__(self, *args, **kwargs): return self.file
# Allows users to use the 'close' function if they want, in case
# the user did not have the AtomicOpen in a "with" block.
def close(self): self.__exit__()
# Unlock the file and close the file object
def __exit__(self, exc_type=None, exc_value=None, traceback=None):
# Release the lock on the file
unlock_file(self.file)
self.file.close()
# Handle exceptions that may have come up during execution, by
# default any exceptions are raised to the user
if (exc_type != None): return False
else: return True
Теперь можно использовать «AtomicOpen» где обычно можно использовать оператор «open».
ПРЕДУПРЕЖДЕНИЕ. Если при столкновении с Windows и Python происходит сбой перед вызовом exit, я не уверен, что такое поведение блокировки.
ПРЕДУПРЕЖДЕНИЕ: Предусмотренная здесь блокировка является консультативной, а не абсолютной. Все потенциально конкурирующие процессы должны использовать класс «AtomicOpen».