防止多个python脚本同时访问单个文件

时间:2019-10-07 16:08:37

标签: python python-2.7 python-imaging-library fcntl

我正在尝试创建一系列图像(每个图像是12个较小图像的合成)。空白的合成图像和较小的成分图像已经存在。我编写了一个python脚本,该脚本将(小)图像在某个位置附加到复合系列中的每个(大)图像上。我希望能够同时为12个位置中的每个位置运行此脚本的多个实例。但是,当两个实例尝试写入同一合成图像时,一个或两个组件图像将无法追加到合成。

如何防止脚本的其他实例访问当前正在访问的文件?

我已经尝试了文件锁定,但是无法使其正常工作(下面的示例)

import sys
from PIL import Image
import fcntl

small = str(sys.argv[1])      # component image (small)
composite = str(sys.argv[2])  # composite image (large)
x_coord = int(sys.argv[3])    # x-coordinate of small image
y_coord = int(sys.argv[4])    # y-coordinate of small image

img = Image.open(small)
fo = open(composite, 'ab')

while True:
    try:
        # Lock the file if not already in use
        fcntl.flock(fo, fcntl.LOCK_EX | fcntl.LOCK_NB)
        break
    except:
        # If file is locked, wait for it to be unlocked
        print("Drat! It's locked!")
        time.sleep(5.)

comp_img = Image.open(fo)
img = img.resize((500,500))
comp_img.paste(img,(x_coord,y_coord))
comp_img.save(composite)

# Unlock the file for other instances to use
fcntl.flock(fo, fcntl.LOCK_UN)

我知道我在try-except块中使用sleep(可能还有很多其他事情)不是最优的,但是我担心它在我可以正常工作时会

0 个答案:

没有答案