Python:锁定目录 [英] Python: Lock directory
问题描述
AFAIK此代码可用于锁定目录:
AFAIK this code can be used to lock a directory:
class LockDirectory(object):
def __init__(self, directory):
assert os.path.exists(directory)
self.directory = directory
def __enter__(self):
self.dir_fd = os.open(self.directory, os.O_RDONLY)
try:
fcntl.flock(self.dir_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError as ex:
if ex.errno != errno.EAGAIN:
raise
raise Exception('Somebody else is locking %r - quitting.' % self.directory)
def __exit__(self, exc_type, exc_val, exc_tb):
self.dir_fd.close()
但是根据此问题的答案,无法锁定目录: Python:锁定目录
But according to the answers of this question locking a directoy is not possible: Python: Lock a directory
上面的代码有什么问题?
What is wrong with above code?
我只需要支持当前的linux版本.没有Windows,Mac或其他Unix.
I only need to support current linux version. No Windows, Mac or other unix.
推荐答案
我稍稍更改了代码,像大多数上下文管理一样添加了return self
,然后使用dup()
,第二个上下文管理将失败.很简单,取消注释fcntl.flock(self.dir_fd,fcntl.LOCK_UN)
I change your code a bit,add return self
like most context manage do,then with dup()
,the second context manage will fail.and the solution is simple,uncommentfcntl.flock(self.dir_fd,fcntl.LOCK_UN)
用于打开文件的模式与群集无关.
The mode used to open the file doesn't matter to flock.
并且您无法聚集在NFS上.
and you cannot flock on NFS.
import os
import fcntl
import time
class LockDirectory(object):
def __init__(self, directory):
assert os.path.exists(directory)
self.directory = directory
def __enter__(self):
self.dir_fd = os.open(self.directory, os.O_RDONLY)
try:
fcntl.flock(self.dir_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError as ex:
raise Exception('Somebody else is locking %r - quitting.' % self.directory)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# fcntl.flock(self.dir_fd,fcntl.LOCK_UN)
os.close(self.dir_fd)
def main():
with LockDirectory("test") as lock:
newfd = os.dup(lock.dir_fd)
with LockDirectory("test") as lock2:
pass
if __name__ == '__main__':
main()
这篇关于Python:锁定目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!