Py学习  »  Python

asyncio REPL(Python 3.8)

Python之美 • 4 年前 • 374 次点击  

前言

我最近都在写一些Python 3.8的新功能介绍的文章,在自己的项目中也在提前体验新的Python版本。为什么我对这个Python 3.8这么有兴趣呢?主要是因为在Python 2停止官方维护的2020年来临之前,Python 3.8是最后一个大版本,虽然还没有公布Python 3.9的发布时间表,但是按过去的经验,我觉得至少等Python 3.8.4发布之后才可能发布Python 3.9.0,那会应该已经在2020年年末了。所以大家最近2年的话题都会是Python 3.8。本周五(2019-05-31)将发布3.8.0 beta 1,这几天开发者们都在抓紧时间合并代码赶上Python 3.8最后一班车。这几天我将陆续分享几个新合并的特性。今天先说 asyncio REPL

REPL

REPL是 Read-Eval-PrintLoop的缩写,是一种简单的,交互式的编程环境:

  • Read。获得用户输入

  • Eval。对输入求值

  • Print。打印,输出求值的结果

  • Loop。循环,可以不断的重复Read-Eval-Print

REPL对于学习一门新的编程语言非常有帮助,你可以再这个交互环境里面通过输出快速验证你的理解是不是正确。CPython自带了一个这样的编程环境:

  1. python

  2. Python 3.7.1 (default, Dec 13 2018, 22:28:16)

  3. [Clang 10.0.0 (clang-1000.11.45.5)] on darwin

  4. Type "help", "copyright", "credits" or "license" for more information.

  5. >>> def a():

  6. ... return 'A'

  7. ...

  8. >>> a()

  9. 'A'

不过官方自带的这个环境功能非常有限,有经验的Python开发者通常会使用IPython,我写的大部分文章里面的代码都在IPython里面执行的, 而且IPython从 7.0开始支持了Async REPL:

  1. ipython

  2. defPython 3.7.1 (default, Dec 13 2018, 22:28:16)

  3. Type 'copyright', 'credits' or 'license' for more information

  4. IPython 7.5.0 -- An enhanced Interactive Python. Type '?' for help.


  5. In [1]: def a():

  6. ...: return 'A'

  7. ...:


  8. In [2]: a()

  9. Out[2]: 'A'


  10. In [3]: import asyncio


  11. In [4]: async def b():

  12. ...: await asyncio.sleep(1)

  13. ...: return 'B'

  14. ...:


  15. In [5]: await b()

  16. Out[5]: 'B'


  17. In [6]: asyncio.run(b())

  18. Out[6]: 'B'

简单地说,就是在IPython里面可以直接使用await,而不必用 asyncio .run(b())。这个在官方REPL里面是不行的:

  1. python

  2. Python 3.7.1 (default, Dec 13 2018, 22:28:16)

  3. [Clang 10.0.0 (clang-1000.11.45.5 )] on darwin

  4. Type "help", "copyright", "credits" or "license" for more information.

  5. >>> import asyncio

  6. >>> async def b():

  7. ... await asyncio.sleep(1)

  8. ... return 'B'

  9. ...

  10. >>> await b()

  11. File "", line 1

  12. SyntaxError: 'await' outside function

是的,await只能在异步函数里面才可以使用。

Python 3.8的asyncio REPL

好消息是官方REPL也与时俱进,支持asyncio REPL了。具体细节可以看延伸阅读链接1:

  1. ./python.exe -m asyncio

  2. asyncio REPL 3.8.0a4+ (heads/master: 8cd5165ba0, May 27 2019, 22:28:15)

  3. [Clang 10.0.0 (clang-1000.11.45.5)] on darwin

  4. Use "await" directly instead of "asyncio.run()".

  5. Type "help", "copyright", "credits" or "license" for more information.

  6. >>> import asyncio

  7. >>> async def b():

  8. ... await asyncio.sleep(1)

  9. ... return 'B'

  10. ...

  11. >>> await b()

  12. 'B'

  13. >>> async def c():

  14. ... await asyncio.sleep(1)

  15. ... return 'C'

  16. ...

  17. >>> task = asyncio.create_task(c())

  18. >>> await task

  19. 'C'

  20. >>> await asyncio.sleep(1)

注意激活REPL不是直接输入python,而是要用 python-m asyncio,另外那个 importasyncio是激活REPL时自动帮你输入的。

延伸阅读

先别看代码,看看你能不能实现这个功能 😋

  1. https://github.com/python/cpython/pull/13472


Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/33731
 
374 次点击