解决这个问题最优雅的方法是什么:
内置函数的工作方式如下
>>> 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()
Run Code Online (Sandbox Code Playgroud)
scr.txt现在包含'111'.
>>> file2.close()
Run Code Online (Sandbox Code Playgroud)
scr.txt被覆盖,现在包含'222'(在Windows上,Python 2.4).
解决方案应该在同一个进程中工作(如上例所示)以及另一个进程打开文件时.
如果崩溃程序不能保持锁定打开,则是首选.
在基于Debian的操作系统(Ubuntu,Debian Squeeze)上,我使用Python(2.7,3.2)fcntl来锁定文件.据我所知,fnctl.flock以某种方式锁定文件,如果另一个客户端想要锁定同一个文件,则会抛出异常.
我构建了一个小例子,我希望抛出一个例外,因为我先锁定文件,然后,我立即尝试再次锁定它:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import fcntl
fcntl.flock(open('/tmp/locktest', 'r'), fcntl.LOCK_EX)
try:
fcntl.flock(open('/tmp/locktest', 'r'), fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print("can't immediately write-lock the file ($!), blocking ...")
else:
print("No error")
Run Code Online (Sandbox Code Playgroud)
但该示例只是打印"无错误".
如果我将此代码分割为两个同时运行的客户端(一个锁定然后等待,另一个在第一个锁已经激活后尝试锁定),我得到相同的行为 - 完全没有效果.
对这种行为的解释是什么?
编辑:
根据nightcracker的要求进行更改,此版本还会打印"No error",尽管我不希望这样:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import fcntl
import time
fcntl.flock(open('/tmp/locktest', 'w'), fcntl.LOCK_EX | fcntl.LOCK_NB)
try:
fcntl.flock(open('/tmp/locktest', 'w'), fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print("can't immediately write-lock the file ($!), blocking ...")
else:
print("No error")
Run Code Online (Sandbox Code Playgroud) 我想打开一个由另一个应用程序定期写入的文件.此应用程序无法修改.因此,当我知道文件未被其他应用程序写入时,我只想打开该文件.
有没有pythonic方式来做到这一点?否则,我如何在Unix和Windows中实现这一目标?
编辑:我会尽力澄清.有没有办法检查当前文件是否已被其他应用程序打开?
我想从这个问题开始.那些其他应用程序读/写是否与现在无关.
我意识到它可能依赖于操作系统,所以现在可能并不真正与python相关.