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
Run script_a.py
. While it is running, start script_b.py
. Both will happily run, but script_b.py
outputs an empty string if the file is currently opened by script_a.py
.
I was expecting an IOError
exception to be raised, telling me the file is already opened, but it didn't happen, instead the file looks empty. Why is that and what would be the proper way to check if it is opened by another process? Would it be ok to simply check if an empty string is returned and try again until something else is read, or is there a more pythonic way?