Python asyncio reads a file and performs another action at intervals

I admit that I am very lazy: I need to get it done pretty quickly and cannot get around the Python3 async module. (Ridiculously, I found the momentum to be quite intuitive.)

I need to read a file object (pipe) that will block from time to time. While doing this, I want to be able to release another activity at set intervals (say every 30 minutes), regardless of whether there is anything to read from the file.

Can anyone help me with a skeleton to do this using python3 asyncio? (I cannot install a third party module like twisted.)

+3


source to share


1 answer


asyncio (as well as other asynchronous libraries like twisted and tornado) does not support non-blocking IO for files - only sockets and pipes are processed asynchronously.

Main reason: Unix systems don't have a good way to handle files. Let's say on Linux any file read will block the operation.

See also https://groups.google.com/forum/#!topic/python-tulip/MvpkQeetWZA

UPD.



For periodic activity on a schedule, I suppose to use asyncio.Task

:

@asyncio.coroutine
def periodic(reader, delay):
    data = yield from reader.read_exactly(100)  # read 100 bytes
    yield from asyncio.sleep(delay)

task = asyncio.Task(reader, 30*60)

      

A fragment assumes an reader

instance asyncio.StreamReader

.

+5


source







All Articles