Read file line by line with asyncio

后端 未结 4 465
无人及你
无人及你 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条回答
  •  -上瘾入骨i
    2021-01-31 09:57

    Your code structure looks good to me, the following code runs fine on my machine:

    import asyncio
    
    PERIOD = 0.5
    
    @asyncio.coroutine
    def readline(f):
        while True:
            data = f.readline()
            if data:
                return data
            yield from asyncio.sleep(PERIOD)
    
    @asyncio.coroutine
    def test():
        with open('test.txt') as f:
            while True:
                line = yield from readline(f)
                print('Got: {!r}'.format(line))
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(test())
    

提交回复
热议问题