0
A
回答
6
你不需要任何第三方庫。只需爲每個請求創建一個線程,啓動線程,然後等待所有這些線程在後臺完成,或者在下載圖像時繼續執行應用程序。
import threading
results = []
def getter(url, dest):
results.append(urllib.urlretreave(url, dest))
threads = []
for x in range(0,10):
t = threading.Thread(target=getter, args=('http://test.com/file %s.png' % x,
'temp/file %s.png' % x))
t.start()
threads.append(t)
# wait for all threads to finish
# You can continue doing whatever you want and
# join the threads when you finally need the results.
# They will fatch your urls in the background without
# blocking your main application.
map(lambda t: t.join(), threads)
您還可以選擇創建一個線程池,將讓urls
和dests
從隊列中。
如果您使用Python 3,它已經在futures
模塊中爲您實施。
2
像這樣的東西應該幫助你
import grequests
urls = ['url1', 'url2', ....] # this should be the list of urls
requests = (grequests.get(u) for u in urls)
responses = grequests.map(requests)
for response in responses:
if 199 < response.status_code < 400:
name = generate_file_name() # generate some name for your image file with extension like example.jpg
with open(name, 'wb') as f: # or save to S3 or something like that
f.write(response.content)
這裏只圖像的下載將是平行的,但每個圖像內容寫入文件將是連續的,所以你可以創建一個線程或做其他事,使之並行或異步
相關問題
- 1. 獲取圖像異步
- 2. 如何從firebase存儲獲取react.js的異步圖像數據?
- 3. 在Azure Blob存儲中獲取圖像
- 4. 存儲圖像並獲取圖像
- 5. 的Android異步獲取圖像
- 6. 插入圖像獲取異步錯誤
- 7. 異步獲取圖像並設置setNeedsDisplay
- 8. DDD和異步存儲庫
- 9. 獲取圖像的URI存儲在isolatedstorage
- 10. 使用iOS存儲和同步圖像
- 11. 異步保存圖像
- 12. 獲取存儲在可繪製圖像中的圖像的URI
- 13. 使用CodeIgniter在mysql中存儲和獲取圖像
- 14. 如何存儲和獲取圖像變量(SESSION)的圖像?
- 15. 異步圖像下載並存儲在一個ImageView數組
- 16. 異步請求圖像後獲取圖像的大小
- 17. 在android中的異步圖像列表和緩存
- 18. 如何:在SD卡中存儲圖像,存儲和獲取配置文件的共享首選圖像路徑
- 19. Node.js存儲圖像。在前端獲取這些圖像
- 20. 如何在Python中異步獲取文件的差異
- 21. 獲取和存儲python類的方法
- 22. 使用Flask(Python)在Google數據存儲中存儲圖像
- 23. 如何從ip攝像頭獲取圖像並將圖像存儲在openCV中
- 24. Flux Utils存儲和異步定時器
- 25. WP7:獲取圖像的名稱哪些圖像存儲在Libary圖片中?
- 26. 獲取存儲在Titanium中PhotoGallery中的圖像的完整圖像路徑
- 27. React Native獲取異步存儲返回未處理的承諾
- 28. 在沒有模塊和Python細節的Python中獲取圖像
- 29. 在OpenCV中存儲圖像和指針
- 30. 如何從圖庫中獲取圖像,獲取圖像名稱並將其保存在內部存儲器中並獲取該圖像的路徑
棒極了。我不知道我到目前爲止還沒有多線程的生活。謝謝 – Diolor
非常簡單而有用的答案! 「地圖」的使用非常好(以前沒有用過,但我現在正在學習它) – Heartinpiece