我有下面的代码,等待一个日志文件出现,它被外部程序保存在那里,当日志文件出现时我打开它,当它仍然被写入,并打印内容,如外部程序正在更新日志文件我要打印出写入它的任何新行。目前我清除打印出来并重新打印整个文本,我想避免,我想只打印新行。另一件需要改进的事情是等待文件出现,而不是仅仅暂停python脚本。
a=0
while a <= 10:
if os.path.isfile(logPath):
infile = file(logPath)
break
a=a+1
time.sleep(1)
fileSize1 = 0
while True:
wx.Yield()
fileSize = os.path.getsize(logPath)
if fileSize > fileSize1:
lines = infile.readlines()
log.Clear()
log.Refresh()
for line in lines:
print line.rstrip()
if "DBG-X: Returning 1" in line:
break
if "DBG-X: Returning 0" in line:
break
fileSize1 = fileSize
infile.seek(0)
答案 0 :(得分:0)
尝试这样的事情......
lastSize = 0
lastLineIndex = 0
while True:
wx.Yield()
fileSize = os.path.getsize(logPath)
if fileSize > lastSize:
lines = infile.readlines()
newLines = 0
for line in lines[lastLineIndex:]:
newLines += 1
print line.rstrip()
lastLineIndex += newLines
if "DBG-X: Returning 1" in line:
break
if "DBG-X: Returning 0" in line:
break
fileSize1 = fileSize
infile.seek(0)
关键位是
for line in lines[lastLineIndex:]:
我们跳过我们已经看过的线。您可以跳过newLines
变量,然后执行lastLineIndex += 1
但我厌恶改变for循环中的lastLineIndex
(这是我为了避免其他问题而选择的习惯语言)