Chino's Studio

Chino's Workspace

马上订阅 Chino's Studio RSS 更新: https://chinomars.github.io/atom.xml

REPL技术分析——Python的交互式

2020年2月12日 00:20

概要

Python是一种解释型语言,通过解释器对代码进行逐行执行,一般的解释器也是这样实现,当然也存在一些优化方法,对代码进行JIT编译,提高执行速度。所以Python的REPL可以说是原生支持的。

Python语言有多种解释器,例如:

  • CPython:C语言实现的Python解释器,一般情况下在Terminal中执行命令python,就会调用CPython解释器执行代码
  • PyPy:前面提到的通过JIT技术提升Python代码执行速度
  • IPython:Python的交互式解释器,底层也是通过调用CPython对代码进行解释执行

回到主题REPL,我们可以以IPython为入口进行分析,进一步对CPython进行分析

IPython

个人习惯,从源码出发分析。IPtyhon的github源码仓,链接,交互式开发的mainloop的代码在这个interactiveshell.py中,我们可以看到,IPython支持一个完整的代码块的交互式运行,采用异步的方式运行以保证一定的用户体验。一个完整的代码块,由用户输入,可以是一行完整的python代码,也可以是多行语法的代码块。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def _run_cell(self, raw_cell:str, store_history:bool, silent:bool, shell_futures:bool):
"""Internal method to run a complete IPython cell."""
coro = self.run_cell_async(
raw_cell,
store_history=store_history,
silent=silent,
shell_futures=shell_futures,
)

# run_cell_async is async, but may not actually need an eventloop.
# when this is the case, we want to run it using the pseudo_sync_runner
# so that code can invoke eventloops (for example via the %run , and
# `%paste` magic.
if self.trio_runner:
runner = self.trio_runner
elif self.should_run_async(raw_cell):
runner = self.loop_runner
else:
runner = _pseudo_sync_runner

try:
return runner(coro)
except BaseException as e:
info = ExecutionInfo(raw_cell, store_history, silent, shell_futures)
result = ExecutionResult(info)
result.error_in_exec = e
self.showtraceback(running_compiled_code=True)
return result
return

继续分析这个run_cell_async:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36...

剩余内容已隐藏

查看完整文章以阅读更多