简体   繁体   中英

reading log files in Python and outputing specific text

I have a piece of code that reads the last line of a log file as the log is being written to. I want to print errors which occur in the logs, basically start printing when line.startswith('Error') and finish printing when line.startwith('End of Error') . My code is below, Could anybody help me with this please?

log = 'C:\mylog.log'
file = open(log, 'r')
res = os.stat(log)
size = res[6]
file.seek(size)

while 1:
    where = file.tell()
    line = file.readline()
    if not line:
        time.sleep(1)
        file.seek(where)
    else:
        if line.startswith('Error'):
        #print lines until you come to 'End of Error'

Initialize a flag before the loop:

in_error = False

Then switch it on and off as needed:

if line.startswith('Error'):
    in_error = True
elif line.startswith('End of Error'):
    print(line)
    in_error = False
if in_error:
    print(line)

使用subprocess模块来简单地运行tail -F (大写F,在GNU平台上可用)并处理输出可能会更容易。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM