【发布时间】:2017-02-09 01:54:15
【问题描述】:
我正在尝试了解 Python(以及一般情况下)中的协程。一直在阅读有关理论、概念和一些示例的信息,但我仍在苦苦挣扎。我了解异步模型(做了一点 Twisted),但还不了解协程。
一个tutorial 给出了这个作为协程示例(我做了一些更改来说明我的问题):
async def download_coroutine(url, number):
"""
A coroutine to download the specified url
"""
request = urllib.request.urlopen(url)
filename = os.path.basename(url)
print("Downloading %s" % url)
with open(filename, 'wb') as file_handle:
while True:
print(number) # prints numbers to view progress
chunk = request.read(1024)
if not chunk:
print("Finished")
break
file_handle.write(chunk)
msg = 'Finished downloading {filename}'.format(filename=filename)
return msg
这是用这个运行的
coroutines = [download_coroutine(url, number) for number, url in enumerate(urls)]
completed, pending = await asyncio.wait(coroutines)
查看生成器协程示例,我可以看到一些 yield 语句。这里什么都没有,而且 urllib 是同步的,AFAIK。
另外,由于代码应该是异步的,我希望看到一系列交错的数字。 (1, 4, 5, 1, 2, ..., "完成", ...) 。我看到的是一个重复以Finished 结尾的数字,然后是另一个数字(3、3、3、3、...“已完成”、1、1、1、1、...、“已完成” " ...)。
在这一点上我很想说教程是错误的,这是一个协程只是因为它前面有异步。
【问题讨论】:
-
你的是协程只是,因为你使用了
async def。它不是一个非常合作的,因为它从不屈服于其他协同程序。所以是的,你的分析是正确的。 -
我最初编写该教程时犯了一个错误。已更新为使用
aiohttp
标签: python python-3.x async-await coroutine