2015-03-27 19 views
9

Tôi sử dụng asyncio và đẹp aiohttp. Ý tưởng chính là tôi yêu cầu máy chủ (nó trả về liên kết) và sau đó tôi muốn tải xuống tệp từ tất cả các liên kết trong song song (giống như trong một example).Tại sao tôi nhận được lỗi "Tác vụ đã bị hủy nhưng đang chờ xử lý" trong Python asyncio?

Code:

import aiohttp 
import asyncio 

@asyncio.coroutine 
def downloader(file): 
    print('Download', file['title']) 
    yield from asyncio.sleep(1.0) # some actions to download 
    print('OK', file['title']) 


def run(): 
    r = yield from aiohttp.request('get', 'my_url.com', True)) 
    raw = yield from r.json() 
    tasks = [] 
    for file in raw['files']: 
     tasks.append(asyncio.async(downloader(file))) 
     asyncio.wait(tasks) 

if __name__ == '__main__': 
    loop = asyncio.get_event_loop() 
    loop.run_until_complete(run()) 

Tuy nhiên, khi tôi cố gắng chạy nó, tôi có nhiều "Tải ..." đầu ra và

Task was destroyed but it is pending! 

Và gì về 'OK + filename'.

Tôi làm cách nào để khắc phục điều đó?

Trả lời

11

Bạn đã quên yield from cuộc gọi đến asyncio.wait. Bạn cũng có thể có vết lõm trên nó sai; bạn chỉ muốn chạy nó sau khi bạn đã lặp lại toàn bộ danh sách raw['files']. Dưới đây là ví dụ hoàn chỉnh với cả hai sai lầm cố định:

import aiohttp 
import asyncio 

@asyncio.coroutine 
def downloader(file): 
    print('Download', file['title']) 
    yield from asyncio.sleep(1.0) # some actions to download 
    print('OK', file['title']) 

@asyncio.coroutine 
def run(): 
    r = yield from aiohttp.request('get', 'my_url.com', True)) 
    raw = yield from r.json() 
    tasks = [] 
    for file in raw['files']: 
     tasks.append(asyncio.async(downloader(file))) 
    yield from asyncio.wait(tasks) 

if __name__ == '__main__': 
    loop = asyncio.get_event_loop() 
    loop.run_until_complete(run()) 

Nếu không có cuộc gọi đến yield from, run thoát ngay lập tức sau khi bạn đã lặp qua toàn bộ danh sách các tập tin, trong đó sẽ có nghĩa là lối ra kịch bản của bạn, gây ra một bó toàn bộ chưa hoàn thành downloader các tác vụ sẽ bị hủy và cảnh báo bạn nhìn thấy sẽ được hiển thị.

+0

Rất cám ơn vì câu trả lời hay – tim

Các vấn đề liên quan