在Python中结束一个睡眠循环

时间:2015-01-08 08:18:45

标签: python loops

我编写了一个包含睡眠循环的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

我想修改这个,所以每当需要超过1小时没有新行时,结束循环并继续脚本。到目前为止,没有成功。

5 个答案:

答案 0 :(得分:1)

只需保留一个柜台:

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

答案 1 :(得分:0)

while 1(其实,应该写为while True)更改为检查循环中花费的时间的条件。

类似的东西:

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

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

答案 2 :(得分:0)

试试这段代码。

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

答案 3 :(得分:0)

您可以更改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

答案 4 :(得分:0)

这个问题的一个重点是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!