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

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

问题描述

最优雅的解决方法是什么:




  • 打开一个文件进行阅读,但只有当它尚未打开

  • 打开一个文件写作,但只有当它尚未打开阅读或写作时,

    内置函数如此工作

     >>> path = rc:\scr.txt
    >>> file1 = open(path,w)
    >>>>打印文件1
    <打开文件'c:\scr.txt',模式'w'在0x019F88D8>
    >>> file2 = open(path,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模块。



    幸运的是,有一个可移植的实现( portalocker )在python cookbook上使用平台适当的方法。



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

      portalocker.lock(file,flags)

    其中flags是portalocker.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天全站免登陆