当前位置: 移动技术网 > IT编程>脚本编程>Python > Python 3.8新特征之asyncio REPL

Python 3.8新特征之asyncio REPL

2019年06月02日  | 移动技术网IT编程  | 我要评论

前言

我最近都在写一些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-print loop 的缩写,是一种简单的,交互式的编程环境:

  • read。获得用户输入
  • eval。对输入求值
  • print。打印,输出求值的结果
  • loop。循环,可以不断的重复read-eval-print

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

 python
python 3.7.1 (default, dec 13 2018, 22:28:16)
[clang 10.0.0 (clang-1000.11.45.5)] on darwin
type "help", "copyright", "credits" or "license" for more information.
>>> def a():
...   return 'a'
...
>>> a()
'a'

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

ipython

defpython 3.7.1 (default, dec 13 2018, 22:28:16)
type 'copyright', 'credits' or 'license' for more information
ipython 7.5.0 -- an enhanced interactive python. type '?' for help.
in [1]: def a():
  ...:   return 'a'
  ...:
in [2]: a()
out[2]: 'a'
in [3]: import asyncio
in [4]: async def b():
  ...:   await asyncio.sleep(1)
  ...:   return 'b'
  ...:
in [5]: await b()
out[5]: 'b'

in [6]: asyncio.run(b())
out[6]: 'b'

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

python

python 3.7.1 (default, dec 13 2018, 22:28:16)
[clang 10.0.0 (clang-1000.11.45.5)] on darwin
type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> async def b():
...   await asyncio.sleep(1)
...   return 'b'
...
>>> await b()
 file "<stdin>", line 1
syntaxerror: 'await' outside function

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

python 3.8的asyncio repl

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

./python.exe -m asyncio
asyncio repl 3.8.0a4+ (heads/master:8cd5165ba0, may 27 2019, 22:28:15)
[clang 10.0.0 (clang-1000.11.45.5)] on darwin
use "await" directly instead of "asyncio.run()".
type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> async def b():
...   await asyncio.sleep(1)
...   return 'b'
...
>>> await b()
'b'
>>> async def c():
...   await asyncio.sleep(1)
...   return 'c'
...
>>> task = asyncio.create_task(c())
>>> await task
'c'
>>> await asyncio.sleep(1)

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

延伸阅读

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

总结

以上所述是小编给大家介绍的python 3.8新特征之asyncio repl,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网