我想了解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' –