首页 > 解决方案 > 使用 readline() 轮询文件的更改适用于 macOS 但不适用于 Debian 9

问题描述

我想“轮询”文件以进行更改。

以下代码在带有 Python 3.8.6 的 macOS 10.15.7 上运行良好,但在带有 Python 3.7.3 的 Debian 9 上却不行。在 Debian 上,当我向要合并的文件添加新行时,它没有被识别并保持打印检查..

from time import sleep
from datetime import datetime
 
wait = 1
    with open('file.log') as fp:
        exit_pooling = False
        while not exit_pooling:
            print("*** check " + str(datetime.now()))
            line = fp.readline()

            if not line:
                sleep(wait)
                continue
            else:
                print('process line')

谢谢!

标签: pythonpython-3.xlinuxdebianeof

解决方案


使用 Python3.6 在 Ubuntu18.04 上按预期工作:

#!/usr/bin/env python3
from time import sleep
from datetime import datetime
from pathlib import Path

wait = 1
with Path('file.log').open() as fp:
    exit_pooling = False
    while not exit_pooling:
        print("*** check " + str(datetime.now()))
        line = fp.readline()
        if not line:
            sleep(wait)
        else:
            print(f'process line: {line}')
            exit_pooling = line.strip() == 'exit'

推荐阅读