【问题标题】:Python 3.5 - Name 'await' is not definedPython 3.5 - 未定义名称“等待”
【发布时间】: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


    【解决方案1】:

    您必须将您的函数声明为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()
    

    【讨论】:

      【解决方案2】:

      您需要将您的函数声明为async 才能使其工作。 await 关键字只有在你的文件中包含一个用async def 声明的函数时才会启用——有关详细信息,请参阅PEP 492

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2018-03-11
          • 2019-01-15
          • 1970-01-01
          • 2021-10-18
          • 2016-05-16
          • 2013-01-26
          • 2021-03-18
          相关资源
          最近更新 更多