使用aiofiles https://github.com/Tinche/aiofiles:
async with aiofiles.open('filename', mode='r') as f:
async for line in f:
print(line)
EDIT 1
正如 @Jashandeep 提到的,你应该关心阻塞操作:
另一种方法是select
and or epoll
:
from select import select
files_to_read, files_to_write, exceptions = select([f1, f2], [f1, f2], [f1, f2], timeout=.1)
The timeout
参数在这里很重要。
see: https://docs.python.org/3/library/select.html#select.select https://docs.python.org/3/library/select.html#select.select
EDIT 2
您可以使用以下方法注册文件以进行读/写:循环.add_reader() https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.add_reader
它在循环内使用内部 EPOLL 处理程序。
EDIT 3
但请记住,Epoll 不适用于常规文件。