4

我正在尝试使用awaitPython 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. 但是为什么在这两个例子中关键字都没有被识别?

4

3 回答 3

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()
于 2015-10-15T14:17:02.753 回答
1

您需要声明您的功能async以使其工作。await仅当您在文件中包含声明的函数时,才会启用该关键字async def- 有关详细信息,请参阅PEP 492

于 2015-10-15T14:17:03.980 回答
1

根据PEP 492await关键字仅在使用新async def语法定义的函数中被识别,这消除了__future__导入的需要。

于 2015-10-15T14:17:29.003 回答