I'm working with a simple Python script to get my head wrapped around the asyncio module. I'm going through the documentation which can be found here
However, I noticed that my installation of Python 3 (version 3.5.3, installed on a raspberry pi) does not recognize async def, but will recognize @asyncio.coroutine. Thus, my script has changed from the tutorial code to:
import asyncio
import datetime
@asyncio.coroutine
def display_date(loop):
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now())
if (loop.time() + 1.0) >= end_time:
break
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()
However, I'm running into syntax errors at await asyncio.sleep(1). Is there any reason for this?? It runs fine on my ubuntu machine (which has python 3.5.1)
await is allowed inside async def function only.
Old-styled coroutines marked by @asyncio.coroutine decorator should use yield from syntax.
You have Python 3.5.1, so just use new syntax, e.g.:
import asyncio import datetime
async def display_date(loop):
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now())
if (loop.time() + 1.0) >= end_time:
break
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With