简体   繁体   English

等待文本文件写入,逐行读取更改并打印

[英]Wait for text file to be written, read changes line by line and print

I have the below code, which waits for a log file to appear, it's being saved there by an external programme, when the log file appears I open it, while it's still being written to, and print the contents, as the log file is being updated by the external programme I want to print out any new lines being written to it. 我有下面的代码,它等待一个日志文件出现,并由一个外部程序保存在该文件中,当该日志文件出现时,我将其打开,同时仍在将其写入并打印内容,因为该日志文件是由外部程序更新,我想打印出写入其中的任何新行。 Currently I clear the print out and re-print the entire text, which I would like to avoid, I would like to only print the new lines. 目前,我要清除打印内容,然后重新打印整个文本,这是我想避免的,我只想打印新行。 Another thing to improve is waiting for the file to appear, rather than just pausing the python script. 要改进的另一件事是等待文件显示,而不是仅暂停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)

Try something like this... 试试这样的东西...

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)

The key bit is 关键是

for line in lines[lastLineIndex:]:

Where we skip the lines we've already seen. 我们跳过已经看到的行的地方。 You can probably skip the newLines variable and just do lastLineIndex += 1 but I've got an aversion to changing lastLineIndex inside the for loop (a habit I've picked up to avoid issues in other languages) 您可能可以跳过newLines变量,只做lastLineIndex += 1但是我不lastLineIndex += 1在for循环中更改lastLineIndex (我习惯于避免其他语言的问题)

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

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