我想了解Python中的协程(以及一般)。一直在阅读理论,概念和几个例子,但我仍在挣扎。我理解异步模型(做了一点扭曲),但没有协程。这是一个协程?
一个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' –