0

I am using linecache to get the lines before the occurrence of a string. But it is not working. I cannot understand what the problem is?

with open(fileName, 'r') as inFile:
    between = False
        for num, line in enumerate(inFile, 1):
        if st_time in line:
            between = True
        if between:
            if 'Broken pipe' in line:
                line1 = linecache.getline(fileName, num-55)
            if 'ERROR' in line1:
                print("yes")
        if en_time in line:
            between = False
mash
  • 35
  • 10
  • Are you in python3? `Popen`'s responses are `bytes` objects -- check `if b'ERROR' in line1:` and etc – Adam Smith Dec 05 '18 at 06:35
  • @AdamSmith Sorry if the question is not clear. I edited the question. I am not asking about popen. I want it replaced. That is why wrote the function(which is working fine) and other code(which is giving no output) – mash Dec 05 '18 at 06:42
  • Suppose if "No route to host" is found, I want to go to 22 lines before that and then check for another word. linecache can go to a specified line number I think – mash Dec 05 '18 at 06:47
  • 1
    Are you sure the offsets are always exactly 22 and 55 lines? Your `grep` pipeline looks for `ERROR` in all the 55 preceding lines, not just the one at offset 55 before the current line. Anyway, without access to a logfile sample, we cannot really hope to repro this. – tripleee Dec 05 '18 at 06:49
  • Related earlier question: https://stackoverflow.com/questions/53519481/what-is-the-subprocess-equivalent-of-this-os-popen-code – tripleee Dec 05 '18 at 07:00
  • The code in the second block doesn't attempt to do anything else than print "YES". Is this just a trivial failure to collect the output at the end? – tripleee Dec 05 '18 at 07:03
  • No. I cannot move further if I am not able to print yes. That is why I stopped there. I know my primary aim is to get output like the first function – mash Dec 05 '18 at 07:06

1 Answers1

1

It was the problem one of you mentioned. Linecache won't store the entire lines, it will only store the line specified. For example line1 = linecache.getline(fileName, num - 22) will store only the (num -22)th line. I thought it would store till the (num-22)th line.

mash
  • 35
  • 10