gpt4 book ai didi

python - 将第三方库转换为 asyncio

转载 作者:行者123 更新时间:2023-12-05 04:49:36 26 4
gpt4 key购买 nike

我有一个执行缓慢阻塞操作的第三方库(在本例中为 azure-cosmos)。我想将它与 asyncio 库一起使用,以利用一定程度的并行性,这样我就可以启动另一个请求,因为一个请求正在等待我们的数据。

我在网上四处寻找,但无法找到关于如何执行外部库包装的具体答案;是不是很简单:

def external_sync_method(*args, **kwargs):
...

async def my_async_code():
args_list = [...]
return await asyncio.gather(*(external_sync_method(*args) for args in args_list))

最佳答案

在单独的线程中异步运行函数 func。

python >= 3.9

https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread

async def my_async_code():
args_list = [...]
return await asyncio.gather(
*(
asyncio.to_thread(external_sync_method, *args)
for args in args_list
)
)

python <3.9

https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor

async def run_sync_method(func, *args, **kwargs):
loop = asyncio.get_running_loop()
func_call = functools.partial(func, *args, **kwargs)
return await loop.run_in_executor(None, func_call)


async def my_async_code():
args_list = [...]
return await asyncio.gather(
*(
run_sync_method(external_sync_method, *args)
for args in args_list
)
)

关于python - 将第三方库转换为 asyncio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67554263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com