Skip to content

IPython - IO 缓存

IPython 会话期间会自动缓存你输入的命令和产生的输出结果。这个缓存系统提供了方便的方式来回顾之前的命令和结果。

IPython 以以下几种方式存储之前的输入:

  • In 字典/列表: In 对象(行为类似列表和字典)将所有输入的命令存储为字符串,使用输入单元格(cell)的序号作为索引。In[1] 获取第一个命令,In[2] 获取第二个,以此类推。
  • _i, _ii, _iii: 这些变量存储最后三个输入字符串(_i 是最近的)。
  • _i<n>: 你可以使用快捷方式 _i<n> 获取特定单元格 n 的输入(例如,_i3 获取 In [3] 的输入)。
  • _ih 列表: 类似于 In,这个列表存储输入历史记录字符串。
In [1]: greeting = "Hello"
In [2]: name = "IPython"
In [3]: full_message = f"{greeting}, {name}!"
In [4]: print(full_message)
# Output: Hello, IPython!
In [5]: _i # Last input
Out[5]: 'print(full_message)'
In [6]: _ii # Second to last input
Out[6]: 'full_message = f"{greeting}, {name}!"'
In [7]: _i3 # Input from In[3]
Out[7]: 'full_message = f"{greeting}, {name}!"'
In [8]: In[1:4] # Slice of inputs (like a list)
Out[8]: ['greeting = "Hello"', 'name = "IPython"', 'full_message = f"{greeting}, {name}!"']
In [9]: _ih[2] # Accessing history list by index
Out[9]: 'name = "IPython"'

注意:In[0] 或 _ih[0] 通常包含空字符串或会话启动信息。

IPython 也缓存命令的结果(输出):

  • Out 字典: 这个字典存储输出对象,将输入单元格序号映射到相应的输出结果。不产生输出的命令(例如赋值语句)不存储在这里。
  • _, __, ___: 这些变量存储最后三个输出对象(_ 是最近的)。这对于在下一次计算中快速重用结果非常有用。
  • _<n>: 你可以使用快捷方式 _<n> 获取特定单元格 n 的输出(例如,_5 获取 Out[5] 的输出)。
  • _oh 字典: 类似于 Out,这个字典存储输出历史记录。
In [1]: 10 * 2
Out[1]: 20
In [2]: 3 + 5
Out[2]: 8
In [3]: _ + __ # Adds the last output (8) and the second-to-last output (20)
Out[3]: 28
In [4]: list(Out.keys()) # Show which cells produced output
Out[4]: [1, 2, 3]
In [5]: Out[2]
Out[5]: 8
In [6]: _2 # Shortcut for Out[2]
Out[6]: 8
In [7]: x = 100 # No output generated
In [8]: Out.get(7, 'No output') # Cell 7 had no output
Out[8]: 'No output'

这些缓存机制显著增强了交互性,让你无需重新输入命令或重新运行计算即可访问之前的结果。