[Tutor] Search error code in a logfile and print all lines until the error code

Alan Gauld alan.gauld at yahoo.co.uk
Thu Nov 29 13:57:40 EST 2018


On 29/11/2018 12:53, Asad wrote:
> Hi All ,
> 
>       I need some help to print error lines from a log file :

I don;t have time right now for a detailed analysis but
there are some obvious starting points:


> f4 = open (r"file1.log", 'r')
> string2=f4.readlines()
> for i in range(len(string2)):

Its usually easier to just use

for line in f4:
    process line here...


>     position=i
>     lastposition =position+1
>     while True:
>          if re.search('ORA-20001: set_patch_metadata not
> called',string2[lastposition]):

You don;t need to use regular expressions for fixed strings.
A regular string search will be more efficient.

if searchString in line

>             break
>          elif lastposition==len(string2)-1:

If you uyse the for line in file idiom you don't need
this check. The loop will never run off the end.

>          break

That break is not indented so will always exit the
loop on the first go round. I'll assume for now its just
a typo or email glitch...

>          else:
>             lastposition += 1
>             errorcheck=string2[position:lastposition]
>          print errorcheck

> I think the logic I am using is correct but need some expert comment to
> make it work also some guidance on how to print all the lines until the
> error is received .

The easiest way to do this is usually to set a flag True
when you hit the start line and then false when you hit
the end. print while the flag is True

for line in file:
   if isStart(line): flag = True
   if isEnd(line): flag = False
   if flag: print line

Now write the isStart(line) and isEnd(line) functions and
you should be good to go.

Sorry if I'm missing something key, as I said I just
skimmed this.


gotta run,
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list