Python 模块 'asyncio' 没有属性 'to_thread'

Python module 'asyncio' has no attribute 'to_thread'

来自 python 的 asyncio 示例:

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 进行线程化的替代方案是什么?

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

的更多信息

最佳答案对我没有帮助,因为我已经在使用 python 3.9。7.and 继续出现错误

File "<conda_path>/python3.9/site-packages/starlette/concurrency.py", line 39, in run_in_threadpool
    return await anyio.to_thread.run_sync(func, *args)
AttributeError: module 'anyio' has no attribute 'to_thread'

我在我的 pypi 安装中发现了一个问题,其中一个包没有更新,需要强制更新。

pip install --upgrade --force-reinstall -r requirements.txt

我的 requirements.txt 包含这些库,因此可能是其中任何一个重新安装并解决了我的问题。

moto
uvicorn
fastapi
gunicorn
dnspython