Python 3.5 - 未定义名称"await"

Mon*_*pit 4 python coroutine async-await python-3.5

我正在尝试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()
Run Code Online (Sandbox Code Playgroud)

我更改了yield from行以使用await关键字:

await asyncio.sleep(delay)

我得到SyntaxError:

  File "./test.py", line 8
    await asyncio.sleep(delay)
                ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

所以我试着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
Run Code Online (Sandbox Code Playgroud)

我使用关键字错了吗?为什么await没有定义?我await这篇文章中得到了我的语法.

只是为了涵盖我的所有基础:

$ /usr/bin/env python --version

Python 3.5.0
Run Code Online (Sandbox Code Playgroud)

编辑:

我想将parens添加到该await行是试图调用一个函数await()- 这就是为什么这不起作用并给我一个NameError.但是为什么关键字在这两个例子中都没有得到认可?

Que*_*Roy 8

您必须声明您的功能async使用await.更换yield from是不够的.

#! /usr/bin/env python
import asyncio

@asyncio.coroutine
async def adder(*args, delay):
    while True:
        await 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()
Run Code Online (Sandbox Code Playgroud)