Mike
Mike

Reputation: 143

Python asyncio cannot work

I want to use asyncio to get the size of a set of images.

Passing in a set of urls, I hope to get three values, (x, y, channel).

However, I cannot get anything.

Are there anythings wrong with my code?

from PIL import Image
from io import BytesIO
import numpy as np
import asyncio
import concurrent.futures
import requests

def get_image_shape(path):
    try:
        img = Image.open(BytesIO(requests.get(path).content))
        arr = np.array(img, dtype = np.uint8)
        return arr.shape
    except:
        return (0,0,0)

async def main(url_list):
    loop = asyncio.get_event_loop()
    futures = [
        loop.run_in_executor(
            None, 
            get_image_shape, 
            url
        )
        for url in url_list]
    for response in await asyncio.gather(*futures):
        pass

loop = asyncio.get_event_loop()
loop.run_until_complete(main(url_list))

#response.result()
#[(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)]

Upvotes: 0

Views: 449

Answers (1)

Chan
Chan

Reputation: 4301

Try this:

from PIL import Image
from io import BytesIO
import numpy as np
import asyncio
import concurrent.futures
import requests

def get_image_shape(path):
    try:
        img = Image.open(BytesIO(requests.get(path).content))
        arr = np.array(img, dtype = np.uint8)
        return arr.shape
    except:
        return (0,0,0)

async def main(url_list):
    loop = asyncio.get_event_loop()
    futures = [
        loop.run_in_executor(
            None, 
            get_image_shape, 
            url
        )
        for url in url_list]
    return [response for response in await asyncio.gather(*futures)]

loop = asyncio.get_event_loop()
response = loop.run_until_complete(main(url_list))

Upvotes: 3

Related Questions