开发者

reading log files in Python and outputing specific text

开发者 https://www.devze.com 2023-04-09 00:35 出处:网络
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\') a

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开发者_如何学JAVA 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)


It may be easier to use the subprocess module to simply run tail -F (capital F, available on GNU platforms) and process the output.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号