在 Python 中打开文件以进行独占访问的最佳方法是什么? [英] What is the best way to open a file for exclusive access in Python?

查看:43
本文介绍了在 Python 中打开文件以进行独占访问的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决这个问题最优雅的方法是什么:

  • 打开一个文件进行读取,但前提是它尚未打开进行写入
  • 打开文件进行写入,但前提是该文件尚未打开进行读取或写入

内置函数是这样工作的

<预><代码>>>>路径 = r"c:scr.txt">>>文件 1 = 打开(路径,w")>>>打印文件 1<打开文件'c:scr.txt',模式'w'在0x019F88D8>>>>file2 = 打开(路径,w")>>>打印文件 2<打开文件'c:scr.txt',模式'w'在0x02332188>>>>file1.write("111")>>>file2.write("222")>>>file1.close()

scr.txt 现在包含111".

<预><代码>>>>file2.close()

scr.txt 被覆盖,现在包含222"(在 Windows 上,Python 2.4).

该解决方案应该在同一进程内(如上例所示)以及在另一个进程打开文件时起作用.
如果崩溃的程序不会使锁保持打开状态,则是首选.

解决方案

我认为没有完全跨平台的方式.在 unix 上, fcntl 模块会为你做这件事.但是在 Windows 上(我假设你是通过路径),你需要使用 win32file 模块.

幸运的是,python 手册中有一个使用平台适当方法的可移植实现(portalocker).

要使用它,打开文件,然后调用:

portalocker.lock(file, flags)

其中标志是用于独占写访问的 portallocker.LOCK_EX,或用于共享、读访问的 LOCK_SH.

What is the most elegant way to solve this:

  • open a file for reading, but only if it is not already opened for writing
  • open a file for writing, but only if it is not already opened for reading or writing

The built-in functions work like this

>>> path = r"c:scr.txt"
>>> file1 = open(path, "w")
>>> print file1
<open file 'c:scr.txt', mode 'w' at 0x019F88D8>
>>> file2 = open(path, "w")
>>> print file2
<open file 'c:scr.txt', mode 'w' at 0x02332188>
>>> file1.write("111")
>>> file2.write("222")
>>> file1.close()

scr.txt now contains '111'.

>>> file2.close()

scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).

The solution should work inside the same process (like in the example above) as well as when another process has opened the file.
It is preferred, if a crashing program will not keep the lock open.

解决方案

I don't think there is a fully crossplatform way. On unix, the fcntl module will do this for you. However on windows (which I assume you are by the paths), you'll need to use the win32file module.

Fortunately, there is a portable implementation (portalocker) using the platform appropriate method at the python cookbook.

To use it, open the file, and then call:

portalocker.lock(file, flags)

where flags are portalocker.LOCK_EX for exclusive write access, or LOCK_SH for shared, read access.

这篇关于在 Python 中打开文件以进行独占访问的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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