Read file line by line with asyncio

后端 未结 4 458
无人及你
无人及你 2021-01-31 09:39

I wish to read several log files as they are written and process their input with asyncio. The code will have to run on windows. From what I understand from searching around bot

4条回答
  •  囚心锁ツ
    2021-01-31 10:11

    Using the aiofiles:

    async with aiofiles.open('filename', mode='r') as f:
        async for line in f:
            print(line)
    

    EDIT 1

    As the @Jashandeep mentioned, you should care about blocking operations:

    Another method is 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 parameter is important here.

    see: https://docs.python.org/3/library/select.html#select.select

    EDIT 2

    You can register a file for read/write with: loop.add_reader()

    It uses internal EPOLL Handler inside the loop.

    EDIT 3

    But remember the Epoll will not work with regular files.

提交回复
热议问题