S
S
Sergey Kutylev2015-11-03 22:05:39
Python
Sergey Kutylev, 2015-11-03 22:05:39

How to read a changing file in python?

There is a log file in which new lines constantly appear.
The task is to constantly read this file; if information appears, then it is necessary to parse it and send it further.
Only tell(), seek() and time.sleep() come to mind. Are there any better options for this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sim3x, 2015-11-04
@sakutylev

https://github.com/bgreenlee/pygtail

Y
Yaroslav Lyzlov, 2015-11-03
@dixoNich

1) Instead of a file, use a base on which you can hang some kind of callback for changes.
2) Either https://github.com/seb-m/pyinotify

S
Sergey Kutylev, 2015-11-03
@sakutylev

Thank you, I just sketched something similar)

import time


def read_realtime(log):
    log.seek(0, 2)
    while True:
        row = log.readline()
        if not row:
            time.sleep(0.1)
            continue
        yield row

log = open("IN1511.log", "r")
log_rows = read_realtime(log)
for row in log_rows:
    print(row)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question