简体   繁体   English

如何在使用 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"

I want to write a Python program on Linux that reads a log file in real time as it is being written, for the purpose of sending an alarm if it detects certain things in the log.我想在 Linux 上编写一个 Python 程序,它在写入日志文件时实时读取日志文件,以便在检测到日志中的某些内容时发送警报。 I want this to use asyncio for several reasons - I'm trying to build a framework that does many things at the same time based on asyncio, and I need the practice.我希望它使用 asyncio 有几个原因——我正在尝试构建一个基于 asyncio 同时做很多事情的框架,我需要练习。

Since I'm using asyncio, I obviously don't want to use a blocking read to wait at the end of the input file for more lines to be written to it.由于我使用的是 asyncio,我显然不想使用阻塞读取在输入文件的末尾等待更多行写入其中。 I suspect I'll have to end up using select, but I'm not sure.我怀疑我最终必须使用 select,但我不确定。

I suspect that this is pretty simple, but I have a hard time finding an example of how to do this, or coming up with one of my own even though I've dabbled a little bit in asyncio before.我怀疑这很简单,但我很难找到一个如何做到这一点的例子,或者想出一个我自己的例子,即使我以前涉足过 asyncio 一点点。 I can read and mostly understand other asyncio examples I find, but for some reason I find it difficult to write asyncio code of my own.我可以阅读并大致理解我发现的其他 asyncio 示例,但由于某种原因,我发现很难编写自己的 asyncio 代码。

Therefore, I'd be very grateful if someone could point me to an example.因此,如果有人能给我举个例子,我将不胜感激。 Bonus points if the same technique also works for reading from stdin rather than a file.如果相同的技术也适用于从 stdin 而不是文件读取,则加分。

I suspect I'll have to end up using select, but I'm not sure.我怀疑我最终必须使用 select,但我不确定。 I suspect that this is pretty simple, but I have a hard time finding an example of how to do this我怀疑这很简单,但是我很难找到如何执行此操作的示例

With asyncio, the idea is that you don't need to select() yourself because asyncio selects for you - after all, a select() or equivalent is at the heart of every event loop.使用 asyncio,想法是您不需要自己select()因为 asyncio 为您选择 - 毕竟, select()或等效项是每个事件循环的核心。 Asyncio provides abstractions like streams that implement a coroutine facade over the async programming model. Asyncio 提供了抽象,比如在异步编程模型上实现协程外观的 There are also the lower-level methods that allow you to hook into select() yourself, but normally you should work with streams.还有一些较低级别的方法可以让您自己挂钩select() ,但通常您应该使用流。

In case of tail -f , you can't use select() because regular files are always readable.tail -f情况下,您不能使用select()因为常规文件始终可读。 When there is no data, you get an EOF and are expected to try again later.当没有数据时,您会收到一个 EOF,并希望稍后再试。 This is why tail -f historically used reads with pauses, with the option to deploy notification APIs like inotify where available.这就是tail -f过去使用暂停读取的原因,并可以选择部署通知 API,如可用的inotify

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

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