【问题标题】:Is there similar functionality in Python REPL to Scala's REPL to reference a previous computation?Python REPL 中是否有与 Scala 的 REPL 类似的功能来引用先前的计算?
【发布时间】:2012-01-10 17:39:27
【问题描述】:

我开始喜欢 Scala REPL 使用 resX 引用先前计算的能力,并且想知道是否有一种方法可以在 Python/bpython/iPython REPL 中访问它。

【问题讨论】:

    标签: python scala read-eval-print-loop


    【解决方案1】:

    默认的 Python 解释器通过名称 _ 操作变量以获得最后返回的值(包括返回它的表达式的 None)。 iPython 将此扩展到 _____ 以及 Out,这是一个包含所有返回结果的字典。

    不过,此功能在交互式解释器中存在。在常规的 python 模块中,_ 是未定义的(除非你定义它)。

    【讨论】:

    • ipython 还允许_N 其中N 是您想要的结果的历史编号
    【解决方案2】:

    看看这个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]
    

    【讨论】:

    • 哇这个回答这么快,我什至无法接受你的回答!非常感谢!!
    猜你喜欢
    • 2012-03-22
    • 1970-01-01
    • 2017-06-21
    • 2012-02-15
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 2018-11-21
    • 2010-12-30
    相关资源
    最近更新 更多