简体   繁体   English

在Python中结束睡眠循环

[英]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: 我编写了一个python脚本,其中包含一个睡眠循环以观看日志文件,等待换行处理:

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. 我想对此进行修改,以便每隔1个小时以上没有换行,结束循环并继续执行脚本。 So far didn't succeed in doing that. 到目前为止,这样做还没有成功。

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

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. while 1 (顺便说一句,应该写为while True )更改为一个条件,该条件可以检查循环所花的时间。

Something like: 就像是:

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

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

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

You can change while to check for 1 hour slot and reset the startTime as below: 您可以更改while以检查1小时的时间段并重置startTime ,如下所示:

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

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. 这个问题的重要一点是连续 1个小时没有新行,因此在新行打印后必须重置计时器。

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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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