Python多个用户同时附加到同一文件 [英] Python Multiple users append to the same file at the same time

查看:203
本文介绍了Python多个用户同时附加到同一文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究可通过网络访问的python脚本,因此将有多个用户试图同时附加到同一文件。我担心的是,这可能会导致争用情况,如果多个用户同时写入同一个文件,并且可能会损坏文件。

I'm working on a python script that will be accessed via the web, so there will be multiple users trying to append to the same file at the same time. My worry is that this might cause a race condition where if multiple users wrote to the same file at the same time and it just might corrupt the file.

例如:

#!/usr/bin/env python

g = open("/somepath/somefile.txt", "a")
new_entry = "foobar"
g.write(new_entry)
g.close

我将为此使用一个锁定文件,因为此操作看起来很冒险。

Will I have to use a lockfile for this as this operation looks risky.

推荐答案

您可以使用文件锁定

import fcntl
new_entry = "foobar"
with open("/somepath/somefile.txt", "a") as g:
    fcntl.flock(g, fcntl.LOCK_EX)
    g.write(new_entry)
    fcntl.flock(g, fcntl.LOCK_UN)

请注意,在某些系统上,如果只写小缓冲区,则不需要锁定,因为在这些系统上添加的是原子

Note that on some systems, locking is not needed if you're only writing small buffers, because appends on these systems are atomic.

这篇关于Python多个用户同时附加到同一文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆