Asynchronous generators
Jonathan Gossage
jgossage at gmail.com
Tue Jun 23 14:04:42 EDT 2020
--
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/runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/local/lib/python3.8/runpy.py", line 87, in _run_code
exec(code, run_globals)
File
"/home/jgossage/EclipseWorkspaces/GlobalVillage/Infrastructure/Play/Async/passwd.py",
line 34, in <module>
_loop.create_task(_rp)
File "/usr/local/lib/python3.8/asyncio/base_events.py", line 431, in
create_task
task = tasks.Task(coro, loop=self, name=name)
TypeError: a coroutine was expected, got <async_generator object
_read_password at 0x7f1f2454b8b0>
More information about the Python-list
mailing list