考虑这两个 python 程序:
script_a.py
:
from datetime import datetime
from time import sleep
while True:
sleep(1)
with open('foo.txt', 'w') as f:
sleep(3)
s = str(datetime.now())
f.write(s)
sleep(3)
script_b.py
:
while True:
with open('foo.txt') as f:
s = f.read()
print s
运行 script_a.py
。在它运行时,启动 script_b.py
。两者都会顺利运行,但如果文件当前由 script_a.py
打开,则 script_b.py
输出一个空字符串。
我原以为会引发 IOError
异常,告诉我文件已经打开,但它并没有发生,相反文件看起来是空的。为什么会这样,检查它是否被另一个进程打开的正确方法是什么?是否可以简单地检查是否返回一个空字符串并重试直到读取其他内容,或者是否有更 pythonic 的方式?
最佳答案
请参阅有关如何在 Python 中打开多个文件的其他答案和评论。如果您已阅读所有内容,但仍想在 POSIX 平台上锁定对文件的访问权限,那么您可以使用 fcntl图书馆。
请记住:A) 其他程序可能会忽略您对文件的锁定,B) 一些网络文件系统没有很好地实现锁定,或者根本没有实现锁定 C) 一定要非常小心释放锁定并避免死锁,因为 flock 不会检测到它 [1] [2] .
例子.... 脚本_a.py
from datetime import datetime
from time import sleep
import fcntl
while True:
sleep(1)
with open('foo.txt', 'w') as f:
s = str(datetime.now())
print datetime.now(), "Waiting for lock"
fcntl.flock(f, fcntl.LOCK_EX)
print datetime.now(), "Lock clear, writing"
sleep(3)
f.write(s)
print datetime.now(), "releasing lock"
fcntl.flock(f, fcntl.LOCK_UN)
脚本_b.py
import fcntl
from datetime import datetime
while True:
with open('foo.txt') as f:
print datetime.now(), "Getting lock"
fcntl.flock(f, fcntl.LOCK_EX)
print datetime.now(), "Got lock, reading file"
s = f.read()
print datetime.now(), "Read file, releasing lock"
fcntl.flock(f, fcntl.LOCK_UN)
print s
希望这对您有所帮助!
关于python - 打开已经打开的文件不会引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22617452/