I'm trying to read a log file under macOS with Python2 (this combination is important, Python 3 works ok, Linux hasn't this problem with both versions).
This file is written by another program at the same time.
Issue: new lines (appeared after last reading cycle) are unavailable for Python. (but I see them with tail -f
). To reproduce you can run reader and writer in the same directory in different terminals (and tail -f out.out
in third terminal if you want to check):
Reader:
import os
import time
def str_num(line):
n_s = line.find('#')
n_e = line[n_s:].find(' ')
print(line)
return int(line[n_s+1: n_s + n_e])
with open('out.out', 'rt') as _file:
while True:
os.path.getsize('out.out')
lines = _file.readlines(1000)
n1 = n2 = -1
if lines:
n1 = str_num(lines[0])
n2 = str_num(lines[-1])
print("%s (%s - %s)" % (len(lines), n1, n2))
time.sleep(1)
writer:
import time
num = 0
with open('out.out', 'w', buffering=1)as _file:
while True:
_file.write("*** String #%s ***\n" % num)
if not num % 100: print(num)
num += 1
time.sleep(0.01)
One workaround I've found is to use tell()
and seek()
to 'reset' file access. Is there any smarter way to resolve this problem?