对示例程序spinner_asyncio.py进行修改使其能运行

学习《流畅的python》第18章 使用asyncio包处理并发,运行示例18-2 spinner_asyncio.py的时候,程序报错如下:
D:\fluentPy\chapter17>python spinner_asyncio.py
  File "D:\fluentPy\chapter17\spinner_asyncio.py", line 30
    spinner = asyncio.async(spin('thinking!'))
                      ^^^^^
SyntaxError: invalid syntax


其实在PyCharm中已经报错了,因为我的环境python311不支持async函数了。在https://docs.python.org/上查到async函数已经被ensure_future函数替代了。
asyncio.async(coro_or_future, *, loop=None)
A deprecated alias to ensure_future().
Deprecated since version 3.4.4.


改过之后运行程序,还是报错:
D:\fluentPy\chapter17>python spinner_asyncio.py
Traceback (most recent call last):
  File "D:\fluentPy\chapter17\spinner_asyncio.py", line 6, in
    @asyncio.coroutine
     ^^^^^^^^^^^^^^^^^
AttributeError: module 'asyncio' has no attribute 'coroutine'. Did you mean: 'coroutines'?


我把python降级到python 3.7.9,问题终于解决:
D:\fluentPy\chapter17>"c:\Program Files\Python37\python" spinner_asyncio.py
spinner object: >
Answer: 42

你可能感兴趣的:(python编程学习,python,asyncio)