Real-time data reading

3

I'm trying to make a tool to read and send (real-time) information from a log to my screen.

So far I've been able to read everything and send the information line by line and send them all to the screen, follow the code.

import time

count = 0
while True:

    arquivo = ('LOG')
    arq = open(arquivo, 'r')
    texto = arq.readlines()
    arq.close()
    count += 1
    print(texto[count])
    time.sleep(5)

The problem is that the program may or may not take a long time to generate a new line in the log, and when it reaches the last line, the problem closes with the error.

print(texto[count])
IndexError: list index out of range

How would I make the program, waiting for the new line to be inserted into the log file?

    
asked by anonymous 15.06.2017 / 22:15

2 answers

3

This example might help you. Read one line at a time until the end of the file. The arq.readline () method returns '' while there are no new rows. In your code you were trying to read all the rows in each iteration of the while.

import time


def monitorar(path):
    with open(path, 'r') as arq:
        while True:
            nova_linha = arq.readline()
            nova_linha = nova_linha.replace('\n', '')
            if nova_linha:
                yield nova_linha
            else:
                time.sleep(1.0)

caminho_arquivo = 'teste.log'
for idx, linha in enumerate(monitorar(caminho_arquivo)):
    print("{:5d}: {}".format(idx, linha))
    
16.06.2017 / 01:39
0

Excellent response from colleague fsola.

I have a subject to make it more pythonic. By replacing replace with the strip, we've narrowed down one line of code.

#Python3
import time

def monitorar(logfile='file.log'):
    with open(logfile) as file:
        while True:
            linha = file.readline().strip()
            if linha:
                yield linha
            else:
                time.sleep(.5)

if __name__ == '__main__':
    logfile = 'file.log'
    for item, linha in enumerate(monitorar(logfile)):
        #print(item, linha)
        #print('%s: %s' % (item, linha))
        print('{:6d}: {}'.format(item, linha))
    
28.06.2017 / 17:13