Consider those two python programs:
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
异常,告诉我文件已经被打开了,但这并没有发生,相反文件看起来是空的。为什么会这样,如何正确地检查它是否被另一个进程打开?是否可以简单地检查返回的空字符串并重试,直到读取到其他内容,还是有更具Python风格的方法?