【问题标题】:"Up Arrow" history in Python on OS X and code.InteractiveConsoleOS X 和 code.InteractiveConsole 上 Python 中的“向上箭头”历史
【发布时间】:2016-04-17 12:42:01
【问题描述】:

我在我的一些 Python 脚本中使用以下技巧进入交互式 Python REPL 会话:

import code; code.InteractiveConsole(locals=globals()).interact()

这通常在工作中的各种 RHEL 机器上运行良好,但在我的笔记本电脑(OS X 10.11.4)上,它似乎在没有 readline 支持的情况下启动 REPL。你可以看到我得到了^[[A^C 垃圾字符。

My-MBP:~ complex$ cat repl.py 
a = 'alpha'
import code; code.InteractiveConsole(locals=globals()).interact()
b = 'beta'


My-MBP:~ complex$ python repl.py 
Python 2.7.10 (default, Oct 23 2015, 19:19:21) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> a
'alpha'
>>> ^[[A^C

如果我直接调用python,REPL 中的向上箭头命令历史记录可以正常工作。

我尝试检查globals() 以寻找一些线索,但在每种情况下它们似乎都是相同的。关于如何解决此问题或在哪里查看的任何想法?

编辑:并显示正确的行为:

My-MBP:~ complex$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 'a'
'a'
>>> 'a'

【问题讨论】:

    标签: python macos readline read-eval-print-loop


    【解决方案1】:

    只需import readline,无论是在脚本中还是在控制台中。

    【讨论】:

    • import readline 确实放弃了箭头命令历史。这很有帮助。但是,为什么我在运行“裸”python 时不必导入截止日期模块?
    • 我不知道。我认为这不是您的安装问题。我在 OSX 10.10 和 ssh 进入 Ubuntu 机器时的行为完全相同。
    【解决方案2】:

    程序rlwrap 总体上解决了这个问题,不仅适用于Python,也适用于其他需要此功能的程序,例如telnet。如果你有 Homebrew(你应该),你可以用 brew install rlwrap 安装它,然后通过在命令的开头插入它来使用它,即rlwrap python repl.py

    【讨论】:

    • 欣赏指向 rlwrap 的指针。但是,我没有安装 Homebrew,也不打算这样做(原因与此处无关)。我想弄清楚内置的python 是如何以及为什么不起作用的。
    猜你喜欢
    • 2011-07-24
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多