模块“asyncio”在Python 3.9.4中没有属性“run”

2024-04-26 17:33:05 发布

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

我正在尝试开始学习asyncio,但我无法获得简单的示例。以前关于此错误的文章指出使用了3.7之前的python版本,但在这里您可以看到我使用的是最新版本(3.9.4)。将代码直接输入python解释器是可行的,但从文件运行代码则不行。知道我做错了什么吗

命令行输出

> python3 --version
Python 3.9.4
> python3 asyncio.py
Traceback (most recent call last):
  File "/home/mmolesworth/courses/asyncio.py", line 22, in <module>
    asyncio.run(main())
AttributeError: module 'asyncio' has no attribute 'run'

asyncio.py内容

import asyncio

async def count():
    print("One")
    await asyncio.sleep(1)
    print("Two")

async def main():
    await asyncio.gather(count(), count(), count())

if __name__ == "__main__":
    import time
    s = time.perf_counter()
    asyncio.run(main())
    elapsed = time.perf_counter() - s
    print(f"{__file__} executed in {elapsed:0.2f} seconds.")

Tags: run代码inpyimport版本asyncioasync