[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Asynchronous generators

I am attempting to learn how to use asyncio and I have been unable to find
any documentation or Internet posts that give information on the principles
underlying asyncio, let alone any examples showing how asynchronous
generators should be used. I have built a toy program to test trying to
read a text file, line by line, and process each line asynchronously. I
wind up with a message complaining that my asynchronous generator is not a
coroutine. I am posting a copy of my program here along with the results
from trying to run it. I am hoping for some suggestions about how to fix
it.  I am using Python 3.8.3 on Ubuntu 20.04

import asyncio
> from pathlib import Path
> import timeit
> async def _read_password() -> str:
>     with Path('/etc/passwd').open() as f:
>         line: str = f.readline()
>         yield line
>     print('read_password has read everything')
> async def main(_rp) -> int:
>     line = ''
>     async for line in _rp:
>         try:
>             print(f'Got line {line}')
>         except StopAsyncIteration:
>             line = None
>     _rp.aclose()
>     return 0
> if __name__ == '__main__':
>     _loop = asyncio.get_event_loop()
>     _rp = _read_password()
>     _m = main(_rp)
>     _loop.create_task(_m)
>     _loop.create_task(_rp)
>     timeit.Timer(_loop.run_until_complete()).timeit()
>     _loop.close()

Here is the output:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/local/lib/python3.8/", line 87, in _run_code
    exec(code, run_globals)
line 34, in <module>
  File "/usr/local/lib/python3.8/asyncio/", line 431, in
    task = tasks.Task(coro, loop=self, name=name)
TypeError: a coroutine was expected, got <async_generator object
_read_password at 0x7f1f2454b8b0>