【发布时间】:2012-01-10 17:39:27
【问题描述】:
我开始喜欢 Scala REPL 使用 resX 引用先前计算的能力,并且想知道是否有一种方法可以在 Python/bpython/iPython REPL 中访问它。
【问题讨论】:
标签: python scala read-eval-print-loop
我开始喜欢 Scala REPL 使用 resX 引用先前计算的能力,并且想知道是否有一种方法可以在 Python/bpython/iPython REPL 中访问它。
【问题讨论】:
标签: python scala read-eval-print-loop
默认的 Python 解释器通过名称 _ 操作变量以获得最后返回的值(包括返回它的表达式的 None)。 iPython 将此扩展到 __ 和 ___ 以及 Out,这是一个包含所有返回结果的字典。
不过,此功能仅在交互式解释器中存在。在常规的 python 模块中,_ 是未定义的(除非你定义它)。
【讨论】:
_N 其中N 是您想要的结果的历史编号
看看这个python启动脚本(Python会寻找一个导出PYTHONSTARTUPvariable,它应该包含脚本的路径,例如$HOME/.pythonrc.py):
作为备份:
h = [None] # history
class Prompt:
"""A prompt a history mechanism.
From http://www.norvig.com/python-iaq.html
"""
def __init__(self, prompt='h[%d] >>> '):
self.prompt = prompt
def __str__(self):
try:
if _ not in h: h.append(_)
except NameError:
pass
return self.prompt % len(h)
def __radd__(self, other):
return str(other) + str(self)
sys.ps1 = Prompt()
sys.ps2 = ' ... '
用法:
h[1] >>> lambda x: x * 2
<function <lambda> at 0xb7dab41c>
h[2] >>> [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
h[3] >>> map(h[1], h[2])
[2, 4, 6, 8, 10]
【讨论】: