Python asyncio 无法工作
Python asyncio cannot work
我想使用 asyncio 获取一组图像的大小。
传入一组url,希望得到三个值,(x, y, channel)
。
但是,我什么也得不到。
我的代码有问题吗?
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)]
试试这个:
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))
我想使用 asyncio 获取一组图像的大小。
传入一组url,希望得到三个值,(x, y, channel)
。
但是,我什么也得不到。
我的代码有问题吗?
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)]
试试这个:
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))