Python模块“asyncio”没有“to_thread”属性

2024-04-24 03:29:21 发布

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

根据python的异步IO示例:

import asyncio
import time
def blocking_io():
    print(f"start blocking_io at {time.strftime('%X')}")
    # Note that time.sleep() can be replaced with any blocking
    # IO-bound operation, such as file operations.
    time.sleep(1)
    print(f"blocking_io complete at {time.strftime('%X')}")

async def main():
    print(f"started main at {time.strftime('%X')}")

    await asyncio.gather(
        asyncio.to_thread(blocking_io),
        asyncio.sleep(1))

    print(f"finished main at {time.strftime('%X')}")


asyncio.run(main())

# Expected output:
#
# started main at 19:50:53
# start blocking_io at 19:50:53
# blocking_io complete at 19:50:54
# finished main at 19:50:54

它正在输出下一个错误:

    asyncio.to_thread(blocking_io),
    AttributeError: module 'asyncio' has no attribute 'to_thread'

此功能是否已被弃用?使用asyncio线程的替代方案是什么


Tags: toioimportasynciotimemaindefsleep
1条回答
网友
1楼 · 发布于 2024-04-24 03:29:21

to_thread仅在python 3.9+中可用,如果您使用的是python 3.8或更早的版本,则可以复制它的source code

async def to_thread(func, /, *args, **kwargs):
    loop = asyncio.get_running_loop()
    ctx = contextvars.copy_context()
    func_call = functools.partial(ctx.run, func, *args, **kwargs)
    return await loop.run_in_executor(None, func_call)

此方法将上下文复制到线程(使用集合ContextVars的当前值)

如果您不需要,只需要一行:

await asyncio.get_running_loop().run_in_executor(None, blocking_io, arg1, arg2)

有关run_in_executor的详细信息

相关问题 更多 >