gpt4 book ai didi

Python:锁定目录

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:02 24 4
gpt4 key购买 nike

据我所知,此代码可用于锁定目录:

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: Lock a directory

上面的代码有什么问题?

我只需要支持当前的 linux 版本。没有 Windows、Mac 或其他 unix。

最佳答案

我稍微改变了你的代码,像大多数上下文管理一样添加return self,然后使用dup(),第二个上下文管理将失败。解决方案是简单,取消注释fcntl.flock(self.dir_fd,fcntl.LOCK_UN)

用于打开文件的模式与 flock 无关。

而且你不能在 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:锁定目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52815858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com