File Locking Using a Cross-Platform API
获得平台无关的文件锁
Credit: Jonathan Feinberg, John Nielsen
转自:http://blog.csdn.net/fdayok/article/details/5263061
问题 Problem
You need to lock files in a cross-platform way between NT and Posix, but the Python standard library offers only platform-specific ways to lock files.
Python标准库未提供锁定文件的平台无关的方法,需要自己编写这样的平台无关(在NT和Posix之间)的锁定文件的代码。
解决 Solution
When the Python standard library itself doesn't offer a cross-platform solution, it's often possible to implement one ourselves:
当Python标准库未提供某功能的平台无关的方法是,经常可以自己实现:
import os
# needs win32all to work on Windows
if os.name == 'nt':
import win32con, win32file, pywintypes
LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
LOCK_SH = 0 # the default
LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
_ _overlapped = pywintypes.OVERLAPPED( )
def lock(file, flags):
hfile = win32file._get_osfhandle(file.fileno( ))
win32file.LockFileEx(hfile, flags, 0, 0xffff0000, _ _overlapped)
def unlock(file):
hfile = win32file._get_osfhandle(file.fileno( ))
win32file.UnlockFileEx(hfile, 0, 0xffff0000, _ _overlapped)
elif os.name == 'posix':
from fcntl import LOCK_EX, LOCK_SH, LOCK_NB
def lock(file, flags):
fcntl.flock(file.fileno( ), flags)
def unlock(file):
fcntl.flock(file.fileno( ), fcntl.LOCK_UN)
else:
raise RuntimeError("PortaLocker only defined for nt and posix platforms")
讨论 Discussion
If you have multiple programs or threads that may want to access a shared file, it's wise to ensure that accesses are synchronized, so that two processes don't try to modify the file contents at the same time. Failure to do so could corrupt the entire file in some cases.
如果有多个程序或线程需要访问一个共享文件,明智的处理是保证访问同步化, 这样2个进程不会同时修改文件. 否则如果没有同步处理,在一些情况下,整个程序可能会崩溃。
This recipe supplies two functions, lock and unlock, that request and release locks on a file, respectively. Using the portalocker.py module is a simple matter of calling the lock function and passing in the file and an argument specifying the kind of lock that is desired:
脚本提供了两个函数: lock 和unlock,分别对文件加锁和释放锁。使用portalocker.py模块很简单,仅需要调用lock函数,传递文件参数和欲加的锁类型参数:
LOCK_SH A shared lock (the default value). This denies all processes write access to the file, including the process that first locks the file. All processes can read the locked file.
共享锁(默认值)。所有进程没有写访问权限,即使是加锁进程也没有。所有进程有读访问权限。
LOCK_EX An exclusive lock. This denies all other processes both read and write access to the file.
排他锁。 除加锁进程外其他进程没有对已加锁文件读写访问权限。
LOCK_NB A nonblocking lock. If this value is specified, the function returns immediately if it is unable to acquire the requested lock. Otherwise, it waits. LOCK_NB can be ORed with either LOCK_SH or LOCK_EX.
非阻塞锁。 如果指定此参数,函数不能获得文件锁就立即返回,否则,函数会等待获得文件锁。LOCK_NB可以同LOCK_SH或LOCK_NB进行or运算。
For example:
例如:
import portalocker
file = open("somefile", "r+")
portalocker.lock(file, portalocker.LOCK_EX)
The implementation of the lock and unlock functions is entirely different on Unix-like systems (where they can rely on functionality made available by the standard fcntl module) and on Windows systems (where they must use the win32file module, part of the very popular win32all package of Windows-specific extensions to Python, authored by Mark Hammond). But the important thing is that, despite the differences in implementation, the functions (and the flags you can pass to the lock function) behave in the same way across platforms. Such cross-platform packaging of differently implemented but equivalent functionality is what lets you write cross-platform applications, which is one of Python's strengths.
lock和unlock地实现在类Unix系统和Windows系统下的完全不同:类Unix系统下依赖于标准模块fcntl提供的功能,Windows系统下使用了非常流行的由Mark Hammond实现的Windows下特定扩展中的win32all模块提供的功能。虽然不同系统下的实现不同,但重要的是,不同平台下文件加解锁的行为是相同的。这样,将不同的实现但相同的行为按照平台无关的方式用模块封装起来,是Python的一大优势:可以编写平台无关的应用。
When you write a cross-platform program, it's nice if the functionality that your program uses is, in turn, encapsulated in a cross-platform way. For file locking in particular, this is helpful to Perl users, who are used to an essentially transparent lock system call across platforms. More generally, if os.name== just does not belong in application-level code. It should ideally always be in the standard library or an application-independent module, as it is here.
当编写跨平台的程序时,如果使用的功能函数已经是经过平台无关的封装处理的,那样会很舒服。特别的,对于文件加锁,perl程序员就不用费心了: Perl提供了透明的跨平台的文件加锁功能。 更一般的,如果os.name不应该出现在应用级别的代码中 ,那么最好它们应该位于Python标准库中 或者在应用无关的模块中(就像 这里的脚本一样).
分享到:
相关推荐
4.24 File Locking Using a Cross-Platform API 4.25 Versioning Filenames 4.26 Module: Versioned Backups 5. Object-Oriented Programming 5.1 Overriding a Built-In Method 5.2 Getting All ...
File Locking Using a Cross-Platform API Recipe 2.29. Versioning Filenames Recipe 2.30. Calculating CRC-64 Cyclic Redundancy Checks Chapter 3. Time and Money Introduction Recipe 3.1. ...
We experimentally demonstrate a simple modulation-free scheme for offset locking the frequency of a laser using buffer gas-induced resonance. Our scheme excludes the limitation of low diffraction ...
High-repetition-rate pulse generation using dual-mode self-injection locking in a Fabry-Perot laser diode
硅微静电加速度计轴间耦合自锁研究,尹永刚,韩丰田,硅微静电悬浮加速度计(MESA)是一种基于差分电容位移检测和静电力反馈的力平衡式三轴惯性仪表,其检验质量依靠六自由度静电悬浮�
锁机制的论文,在jdk1.6以后引入的偏向锁技术大大增加了以往重锁sychronized的性能
UL 498F:2020 Plugs, Socket-Outlets and Couplers with Arcuate (Locking Type) Contacts -最新完整英文版(88页).pdf
TI AR7 flash partition table.
provide all the vectors, so that EQ creation response can decide which one to use.
Asus Eee PC extras for Linux v2.13.6.
32-bit compatibility support for ELF format executables and core dumps.
The order of these masks is important. Matching masks will be seen first and the left over flags will end up showing by themselves.
Using novel phase locking cues, the algorithm performs surprisingly well down to SNR values as low as 5dB, where the performance of the baseline algorithm used for comparison drops considerably....
We experimentally demonstrate an ultrafast mode-locker based on a CoSb3 skutterudite topological insulator for femtosecond mode-locking of a fiber laser. The mode-locker was implemented on a side-...
声光调QNd:YVO4激光器锁模问题探讨,黄海涛,钟艳,在一声光调QNd:YVO4激光器中出现了调Q锁模现象,最大调制深度达90%。通过引入增益牵引效应,我们解释了该现象。所谓增益牵引效应,即
资源分类:Python库 所属语言:Python 资源全名:locking-1.1.4.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
Mode-locking of a terahertz laser by direct phase synchronization
We demonstrate a frequency locking method using the fluorescence spectrum of an Yb atomic beam as a frequency reference. For unresolved fluorescence peaks, we make the spectrum of the even isotopes ...
Unreliable Guide to Locking -by Rusty Russell-中文版 .pdf
.\Samples\delphi\PlatformDemos Delphi FireMonkey and cross-platform samples (Delphi XE2+) .\Samples\delphi\SocketDemos Delphi Win32/Win64 Socket sample applications (all Delphi versions) .\Samples\...