如何在使用 Python 3 和 asyncio 实时写入文件时读取文件,例如 "tail -f"

How to read a file as it is being written in real time with Python 3 and asyncio, like "tail -f"

我想在 Linux 上编写一个 Python 程序,它在写入日志文件时实时读取日志文件,目的是在检测到日志中的某些内容时发送警报日志。我希望它使用 asyncio 有几个原因 - 我正在尝试构建一个基于 asyncio 同时做很多事情的框架,我需要实践。

因为我使用的是 asyncio,所以我显然不想使用阻塞读取来等待输入文件的末尾写入更多行。我怀疑我最终不得不使用 select,但我不确定。

我怀疑这很简单,但我很难找到一个如何执行此操作的示例,或者想出一个我自己的示例,即使我之前已经涉足了一点 asyncio。我可以阅读并基本理解我找到的其他 asyncio 示例,但出于某种原因,我发现很难编写自己的 asyncio 代码。

因此,如果有人能给我举个例子,我将不胜感激。如果相同的技术也适用于从标准输入而不是文件读取,则加分。

I suspect I'll have to end up using select, but I'm not sure. I suspect that this is pretty simple, but I have a hard time finding an example of how to do this

使用 asyncio 的想法是您不需要 select() 自己,因为 asyncio 会为您选择 - 毕竟,select() 或等效项是每个事件循环的核心。 Asyncio 提供像 streams that implement a coroutine facade over the async programming model. There are also the lower-level 方法这样的抽象,允许您自己连接到 select(),但通常您应该使用流。

tail -f 的情况下,您不能使用 select(),因为常规文件总是可读的。当没有数据时,您会收到一个 EOF,并希望稍后重试。这就是为什么 tail -f 过去使用带暂停的读取,并且可以选择部署 inotify 等可用的通知 API。