我正在尝试使用await
Python 3.5 中协程的新语法。
我有一个像这样的简单例子:
#! /usr/bin/env python
import asyncio
@asyncio.coroutine
def adder(*args, delay):
while True:
yield from asyncio.sleep(delay)
print(sum(args))
def main():
asyncio.Task(adder(1, 2, 3, delay=5))
asyncio.Task(adder(10, 20, delay=3))
loop = asyncio.get_event_loop()
loop.run_forever()
if __name__ == "__main__":
main()
我更改了yield from
行以使用await
关键字:
await asyncio.sleep(delay)
我得到SyntaxError
:
File "./test.py", line 8
await asyncio.sleep(delay)
^
SyntaxError: invalid syntax
所以我试着await (asyncio.sleep(delay))
看看会发生什么:
Task exception was never retrieved
future: <Task finished coro=<adder() done, defined at c:\python35\Lib\asyncio\coroutines.py:198> exception=NameError("name 'await' is not defined",)>
Traceback (most recent call last):
File "c:\python35\Lib\asyncio\tasks.py", line 239, in _step
result = coro.send(value)
File "c:\python35\Lib\asyncio\coroutines.py", line 200, in coro
res = func(*args, **kw)
File "./test.py", line 8, in adder
await (asyncio.sleep(delay))
NameError: name 'await' is not defined
Task exception was never retrieved
future: <Task finished coro=<adder() done, defined at c:\python35\Lib\asyncio\coroutines.py:198> exception=NameError("name 'await' is not defined",)>
Traceback (most recent call last):
File "c:\python35\Lib\asyncio\tasks.py", line 239, in _step
result = coro.send(value)
File "c:\python35\Lib\asyncio\coroutines.py", line 200, in coro
res = func(*args, **kw)
File "./test.py", line 8, in adder
await (asyncio.sleep(delay))
NameError: name 'await' is not defined
我是否使用了错误的关键字?为什么await
没有定义?我从这篇文章中await
得到了我的语法。
只是为了涵盖我的所有基础:
$ /usr/bin/env python --version
Python 3.5.0
编辑:
我想将括号添加到该await
行是试图调用一个函数await()
- 这就是为什么它不起作用并给我一个NameError
. 但是为什么在这两个例子中关键字都没有被识别?