在python中一致地读写文件 [英] Consistent reading and writing a file in python

查看:32
本文介绍了在python中一致地读写文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 初学者,面临以下问题:我有一个脚本定期读取设置文件并根据这些设置执行某些操作.我有另一个由某些 UI 触发的脚本,该脚本使用用户输入值写入设置文件.我使用 ConfigParser 模块来读取和写入文件.

I'm a Python beginner and facing the following : I have a script periodically reading a settings file and doing something according to those settings . I have another script triggered by some UI that writes the settings file with user input values. I use the ConfigParser module to both read and write the file.

我想知道这个场景是否能够导致不一致的状态(比如在读取设置文件的过程中,另一个脚本开始写入).我不知道幕后是否有任何机制可以自动防止这种情况.

I am wondering if this scenario is capable of leading into an inconsistent state (like in middle of reading the settings file, the other script begins writing). I am unaware if there are any mechanism behind the scene to automatically protect against this situations.

如果可能出现这种不一致,我可以使用什么来同步两个脚本并保持操作的完整性?

If such inconsistencies are possible, what could I use to synchronize both scripts and mantain the integrity of the operations ?

推荐答案

我是 Python 初学者,面临以下问题:我有一个脚本定期读取设置文件并根据这些设置执行某些操作.我有另一个由某些 UI 触发的脚本,该脚本使用用户输入值写入设置文件.

I'm a Python beginner and facing the following : I have a script periodically reading a settings file and doing something according to those settings . I have another script triggered by some UI that writes the settings file with user input values.

当读者读取而作者写入文件时,可能存在竞争条件,因此读者可能会在文件不完整的情况下读取文件.

There may be a race condition when the reader reads while the writer writes to the file, so that the reader may read the file while it is incomplete.

您可以通过在读取和写入时锁定文件来防止这种竞争(参见 Linux flock()Python 锁文件模块),这样读者就不会发现文件不完整.

You can protect from this race by locking the file while reading and writing (see Linux flock() or Python lockfile module), so that the reader never observes the file incomplete.

或者,更好的是,您可以先写入一个临时文件,完成后 rename 原子地将其重命名为最终名称.这样读者和作者永远不会阻塞:

Or, better, you can first write into a temporary file and when done rename it to the final name atomically. This way the reader and writer never block:

def write_config(config, filename):
    tmp_filename = filename + "~"
    with open(tmp_filename, 'wb') as file:
        config.write(file)
    os.rename(tmp_filename, filename)

当作者使用上述方法时,读者无需更改.

When the writer uses the above method no changes are required to the reader.

这篇关于在python中一致地读写文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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