Learner
Learner

Reputation: 51

End a sleep loop in Python

I've written a python script that contains a sleep loop to watch a log file, waiting for a new line to handle:

file = open('logFile.log', 'r')
while 1:
    where = file.tell()
    line = file.readline()
    if not line:
        time.sleep(1)
        file.seek(where)
    else:
        print line, # already has newline

I'd like to modify this so whenever it takes more than 1 hour without new lines, end the loop and continue the script. So far didn't succeed in doing that.

Upvotes: 1

Views: 115

Answers (5)

Hunter Zhao
Hunter Zhao

Reputation: 4659

One important point to this issue is that there is no new line for 1 hour CONTINUOUSLY, so it's really necessary to reset the time counter after a new line prints.

count = 0
one_hour = 60 * 60
file = open('logFile.log', 'r')
while 1:
    where = file.tell()
    line = file.readline()
    if not line:
        count = count + 1
        if count >= one_hour:
          break
        time.sleep(1)
        file.seek(where)
    else:
        print line
        count = 0   # Here needs to reset the time couter!

Upvotes: 0

ErikR
ErikR

Reputation: 52049

Just keep a counter:

count = 0
file = open('logFile.log', 'r')
while 1:
    where = file.tell()
    line = file.readline()
    if not line:
        count = count + 1
        if count >= 3600:
          break
        time.sleep(1)
        file.seek(where)
    else:
        print line, # already has newline
        count = 0
# if you get here an hour without any newlines has passed

Upvotes: 1

venpa
venpa

Reputation: 4318

You can change while to check for 1 hour slot and reset the startTime as below:

file = open('logFile.log', 'r')
startTime = time.time()
while (time.time()-startTime) >= 3600:
    where = file.tell()
    line = file.readline()
    if not line:
        time.sleep(1)
        file.seek(where)
    else:
        startTime = time.time() #record the last time output was available
        print line, # already has newline

Upvotes: 0

kvivek
kvivek

Reputation: 3491

Try this piece of Code.

file = open('logFile.log', 'r')

while True:
    timeWait = 60*60 # Change the Value to something less to check whether the code works properly or not.
    where = file.tell()
    line = file.readline()
    if not line:
        time.sleep(1)
        timeWait = timeWait - 1
        file.seek(where)
        if timeWait == 0:
            break
    else:
        print line

Upvotes: 0

unwind
unwind

Reputation: 399969

Change the while 1 (which, btw, should really be written as while True) to a condition that checks how long time has been spent in the loop.

Something like:

file = ...
now = time.time()

while time.time() - now < 1 * 60 * 60:

Upvotes: 0

Related Questions