我有一个python程序,它使用asyncioawait模块。这是我从
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将在使用SyntaxError关键字定义的函数内部以外的任何地方使用时引发async,而不管它是否已使用@asyncio.coroutine装饰器进行协程。

import asyncio

async def test():
    pass


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

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

关于python - await asyncio.wait(协程)语法无效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38753312/

10-16 07:02