I\'d like to make the output of tail -F or something similar available to me in Python without blocking or locking. I\'ve found some really old code to do that here, but I\'
Adapting Ijaz Ahmad Khan's answer to only yield lines when they are completely written (lines end with a newline char) gives a pythonic solution with no external dependencies:
def follow(file) -> Iterator[str]:
""" Yield each line from a file as they are written. """
line = ''
while True:
tmp = file.readline()
if tmp is not None:
line += tmp
if line.endswith("\n"):
yield line
line = ''
else:
time.sleep(0.1)
if __name__ == '__main__':
for line in follow(open("test.txt", 'r')):
print(line, end='')