设为首页 收藏本站
查看: 911|回复: 0

[经验分享] File Locking Using a Cross-Platform API(python 跨平台文件锁实现)

[复制链接]

尚未签到

发表于 2017-5-7 14:56:21 | 显示全部楼层 |阅读模式
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标准库中 或者在应用无关的模块中(就像 这里的脚本一样).

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-374313-1-1.html 上篇帖子: 最大公约数欧几里德算法及Python实现 下篇帖子: 包安装Python识别验证码的开源工具 包安装
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表