为什么我不能在gdal模块中等待readasarray方法?

2024-09-27 09:26:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试将几个远程图像读入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))

Tags: 方法in图像loopasynctimemaindef
1条回答
网友
1楼 · 发布于 2024-09-27 09:26:36

您的想法是正确的:一般来说,库函数是以同步(阻塞)的方式执行的,除非库是显式编写的以支持异步执行(例如,通过使用非阻塞I/O),例如aiofilesaiohttp。你知道吗

要使用希望异步执行的同步调用,可以使用loop.run_in_executor。这只不过是将计算卸载到一个单独的线程或进程中,并将其包装起来,使其行为类似于协同程序。示例如here

import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

asyncio.run(main())

但是,如果您的应用程序没有使用任何真正的异步特性,那么您最好直接使用concurrent.futures池并以这种方式实现并发。你知道吗

相关问题 更多 >

    热门问题