Tinche / aiofiles

File support for asyncio
Apache License 2.0
2.67k stars 149 forks source link

Read a file in binary mode from stdin using coroutine #45

Open srbcheema1 opened 6 years ago

srbcheema1 commented 6 years ago

I have used aiofiles to read files if we have path to the file

#! /usr/bin/python3.6
import asyncio
import aiofiles

async def read_input():
    async with aiofiles.open('hello.txt', mode='rb') as f:
        while True:
            inp = await f.read(4)
            if not inp: break
            print('got :' , inp)

async def main():
    await asyncio.wait([read_input()])

event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(main())
event_loop.run_forever()

I need to read the file from standard input as ./reader.py < file.txt The above code reads file as binary. But I need to read stdin as binary using coroutines. I am unable to figure out any way to do that.

Regards, Sarbjit Singh

srbcheema1 commented 6 years ago

I am posting possible solutions to my own question.

the first soln is using aiofiles:

async def read_input():
    async with aiofiles.open('/dev/stdin', mode='rb') as f:
        while True:
            inp = await f.read(4)
            if not inp: break
            print('got :' , inp)

it is platform specific doesn't work on windows.

Another possible solution to this problem is using an feature of aioconsole:

async def read_input():
    stdin, _ = await aioconsole.get_standard_streams()
    while True:
        line = await stdin.read(4)
        if not line: break
        print('got',line)

this seems more robust and platform independent.

Dont know if they are standard ways to accomplish this task or is there any other better way to do it. You may suggest in comments which one is better or may suggest any other solution to it :)

You may close the issue its solved from my side :)