【问题标题】:await asyncio.wait(coroutines) invalid syntaxawait asyncio.wait(coroutines) 语法无效
【发布时间】:2016-12-09 17:58:19
【问题描述】:

我有一个使用asyncioawait 模块的python 程序。这是我从中获取的示例程序 here

import asyncio
import os
import urllib.request
import await

@asyncio.coroutine
def download_coroutine(url):
    """
    A coroutine to download the specified url
    """
    request = urllib.request.urlopen(url)
    filename = os.path.basename(url)

    with open(filename, 'wb') as file_handle:
        while True:
            chunk = request.read(1024)
            if not chunk:
                break
            file_handle.write(chunk)
    msg = 'Finished downloading {filename}'.format(filename=filename)
    return msg

@asyncio.coroutine
def main(urls):
    """
    Creates a group of coroutines and waits for them to finish
    """
    coroutines = [download_coroutine(url) for url in urls]
    completed, pending = await asyncio.wait(coroutines)
    for item in completed:
        print(item.result())


if __name__ == '__main__':
    urls = ["http://www.irs.gov/pub/irs-pdf/f1040.pdf",
            "http://www.irs.gov/pub/irs-pdf/f1040a.pdf",
            "http://www.irs.gov/pub/irs-pdf/f1040ez.pdf",
            "http://www.irs.gov/pub/irs-pdf/f1040es.pdf",
            "http://www.irs.gov/pub/irs-pdf/f1040sb.pdf"]

    event_loop = asyncio.get_event_loop()
    try:
        event_loop.run_until_complete(main(urls))
    finally:
        event_loop.close()

我正在使用python 3.5.1

C:\Anaconda3\python.exe "C:\Users\XXXXXXS\AppData\Roaming\JetBrains\PyCharm Community Edition 2016.1\helpers\pydev\pydevconsole.py" 49950 49951
Python 3.5.1 |Anaconda 2.4.0 (64-bit)| (default, Jun 15 2016, 15:29:36) [MSC v.1900 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

当我尝试运行它时,我收到以下错误。

  File "C:/Cubic/playpen/python/concepts/advanced/coroutines.py", line 29
    completed, pending = await asyncio.wait(coroutines)
                                     ^
SyntaxError: invalid syntax

我同时安装了 asyncio 和 await。

我已经尝试过同样的事情,我也没有遇到任何语法错误。

C:\playpen\python>python
Python 3.5.1 |Anaconda 2.4.0 (64-bit)| (default, Jun 15 2016, 15:29:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> async def foo():
...   await bar
...

【问题讨论】:

  • 您正在导入一个名为 await 的模块并隐藏关键字。删除导入。

标签: python coroutine python-asyncio


【解决方案1】:

await 将在使用async 关键字定义的函数内部以外的任何地方使用时引发SyntaxError,无论它是否已使用@asyncio.coroutine 装饰器成为协程。

import asyncio

async def test():
    pass


async def foo():
    await test()  # No exception raised.

@asyncio.coroutine
def bar():
    await test()  # Exception raised.

【讨论】:

    【解决方案2】:

    你的文章说:

    在 Python 3.5 中添加了 async 和 await 关键字来定义原生协程,并与基于生成器的协程相比,使它们成为不同的类型。如果您想深入了解 async 和 await,请查看 PEP 492。

    这意味着这些 kws 在 Python 3.4 中无效。

    我现在安装了 python 3.5 并尝试了 python 解释器

    foo@foo-host:~$ python3.5  
    Python 3.5.0+ (default, Oct 11 2015, 09:05:38)  
    [GCC 5.2.1 20151010] on linux  
    Type "help", "copyright", "credits" or "license" for more information.  
    >>> async def foo():  
    ...     await bar  
    ...   
    >>>   
    

    没有语法错误。

    【讨论】:

    • @liv2hak:您可能已经安装了多个 Python 解释器,但对您使用的是哪一个感到困惑。
    • 已编辑。运行交互式解释器时检查版本
    • @LuisMasuelli - 我已经在上面更新了。我也得到了同样的结果。
    【解决方案3】:

    这里有两个不同的问题。

    1. 正如dirn 在他的评论中提到的,您不应该导入awaitawait 是 Python 3.5 中的内置关键字。所以,删除import await

    2. 你已经混合了@asyncio.coroutine 装饰器和await 关键字(正如2Cubed 提到的那样)。代替装饰器,使用async def,如您链接到的example 所示。换句话说,而不是:

    @asyncio.coroutine def 下载协程(网址):

    使用:

    async def download_coroutine(url):
    

    main 执行相同操作。

    如果您进行这些更改,您的代码应该在 Python 3.5 下运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-08
      • 2021-01-13
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      • 2019-03-19
      • 2016-01-11
      • 2013-06-17
      相关资源
      最近更新 更多