我尝试将几个远程图像读入python并将这些图像读入numpyray,我尝试使用async来增强我的工作流程,但是我遇到了如下错误此:类型错误:对象numpy.ndarray公司不能用在'await'表达式中,我想知道是不是因为readasarray方法不是异步的,所以如果我必须使它异步,我将不得不用我的语言重写这个方法在这里是我的一些代码:
async def taskIO_1():
in_ds = gdal.Open(a[0])
data1 = await in_ds.GetRasterBand(1).ReadAsArray()
async def taskIO_2():
in_ds = gdal.Open(a[1])
data2 = await in_ds.GetRasterBand(1).ReadAsArray()
async def main():
tasks = [taskIO_1(), taskIO_2()]
done,pending = await asyncio.wait(tasks)
for r in done:
print(r.result())
if __name__ == '__main__':
start = time.time()
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.close()
print(float(time.time()-start))
您的想法是正确的:一般来说,库函数是以同步(阻塞)的方式执行的,除非库是显式编写的以支持异步执行(例如,通过使用非阻塞I/O),例如aiofiles或aiohttp。你知道吗
要使用希望异步执行的同步调用,可以使用
loop.run_in_executor
。这只不过是将计算卸载到一个单独的线程或进程中,并将其包装起来,使其行为类似于协同程序。示例如here:但是,如果您的应用程序没有使用任何真正的异步特性,那么您最好直接使用
concurrent.futures
池并以这种方式实现并发。你知道吗相关问题 更多 >
编程相关推荐