Reputation: 339
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)
Upvotes: 3
Views: 2675
Reputation: 339
I performed a re-flash of Raspbian on the belligerent little thing. It appears to work now. The odd thing is that the image is the 2019-11-29 version. Weird.
Upvotes: 0
Reputation: 17366
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()
Upvotes: 2
Reputation: 39516
async def
and await
- are newer syntax that avaliable only since Python 3.5. If you Python doesn't recognize async def
it won't recognize await
either.
I hardly believe that some 3.5.3 version doesn't have this syntax implemented for some reason. It's much higher possibility that you're just using older python version. Check it adding to code something like:
import sys
print(sys.version)
It'll show Python version you're running.
Btw, asyncio
is standard lib module, you shouldn't install it with pip
at all.
Upvotes: 0