【发布时间】:2016-01-14 00:58:46
【问题描述】:
我正在尝试在 Python 3.5 中使用新的await 协程语法。
我有一个这样的简单例子:
#! /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 没有定义?我从this post. 得到了我的await 语法
只是为了覆盖我所有的基础:
$ /usr/bin/env python --version
Python 3.5.0
编辑:
我想将括号添加到await 行是试图调用函数await() - 这就是为什么它不起作用并给我一个NameError。但是为什么在这两个例子中关键字都没有被识别?
【问题讨论】:
标签: python async-await coroutine python-3.5