I am having problems wrapping my head around how coroutines are connected together. In a slightly less trivial example than hello world or factorials, I would like to have a loop that constantly monitors the time the file changed and then prints the time when the file is affected:
#!/usr/bin/env python3 import os import asyncio @asyncio.coroutine def pathmonitor(path): modtime = os.path.getmtime(path) while True: new_time = os.path.getmtime(path) if new_time != modtime: modtime = new_time yield modtime yield from asyncio.sleep(1) @asyncio.coroutine def printer(): while True: modtime = yield from pathmonitor('/home/users/gnr/tempfile') print(modtime) loop = asyncio.get_event_loop() loop.run_until_complete(printer()) loop.run_forever()
I expect this to work - however, when I run it, I get:
RuntimeError: Task got bad yield: 1426449327.2590399
What am I doing wrong here?
UPDATE: see my answer below for an example of an observer pattern (i.e. effectively allowing multiple registrars to receive updates when a file is touched) without using callbacks (you should use Tasks).
UPDATE2: there is a better fix for this: 3.5 async for (asynchronous iterators): https://www.python.org/dev/peps/pep-0492/
source share