仅从文件中获取新行

Adi*_*sak 5 python logging python-2.7 python-3.x

目前我有这段代码,但它读取所有行,然后使用 while True 语句观察文件:

with open('/var/log/logfile.log') as f:
        while True:
            line = f.readline()
            if not line:
                time.sleep(1)
            else:
                print(line)
Run Code Online (Sandbox Code Playgroud)

实际上,我只需要在打开文件时已检测到的行之后添加新行 - 有人可以帮助我吗?也许还有比 while 语句更好的观看方式?

另一个问题是,在 Linux 机器上,脚本实际上锁定了文件,因此在我再次关闭脚本之前无法写入该文件。在 OS X 上它运行良好。如果有一个解决这个问题的想法也可能很好。

希望有人一直在从事类似的工作。

Pab*_*lgo 5

您最初可以完全读取该文件,然后关闭它,并在其上保留更改监视器,该监视器在下面使用轮询实现。

import time

filePath = '/var/log/logfile.log'

lastLine = None
with open(filePath,'r') as f:
        while True:
            line = f.readline()
            if not line:
                break
            print(line)
            lastLine = line

while True:
    with open(filePath,'r') as f:
        lines = f.readlines()
    if lines[-1] != lastLine:
        lastLine = lines[-1]
        print(lines[-1])
    time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

但您也可以使用类似以下描述的工具:无需轮询即可检测文件更改