在像交互式python shell这样的shell中,你通常可以使用箭头键在当前行中移动,或者获得之前的命令(向上箭头)等。

但当我ssh到另一台机器并在那里启动python后,我得到了如下会话:

>>> import os 
>>> ^[[A    

最后一个字符来自箭头向上。或者,使用箭头向左:

>>> impor^[[D

我该如何解决这个问题?

在常规bash中,方向键工作正常。奇怪的行为只是在交互的python(或perl等)shell中。


当前回答

以下是在ubuntu 12.04的python 3.3中对我有效的步骤。

1)打开终端,输入sudo apt-get install libreadline-dev

2)从http://www.python.org/ftp/python/3.3.2/Python-3.3.2.tar.xz下载python 3.3.2的源文件

3)解压它并导航到shell中的Python-3.3.2/目录

4)执行以下命令:

./configure
make
make test
sudo make install

其他回答

在Mac升级到High Sierra后受到影响,这成功地解决了我的问题:

brew unlink python
xcode-select --install
brew install python

您可以通过以下命令从“sh”切换到“bash”

$ /sh/bash

Readline模块已弃用,在最新的python版本中,当在python shell中执行quit()或exit()时,该模块将导致无效指针错误。 PIP安装gnureadline代替

在MacOsx上,我通过重新安装readline来解决这个问题

brew reinstall readline

在OS X上,使用python 3.5和virtualenv

$ pip install gnureadline

在解释器中做到:

import gnureadline

现在方向键可以正常工作了。


更多信息…

注意,自2015年10月1日起,readline已被弃用(来源https://github.com/ludwigschwardt/python-readline)

使用gnureadline代替(参见:https://github.com/ludwigschwardt/python-gnureadline)

如果我使用python 3.5安装readline而不是gnureadline,在尝试在解释器中导入后,我会收到错误:

>>> import readline
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dlopen(/Users/pi/tmp/python-readline-test/.venv/lib/python3.5/readline.so, 2): Library not loaded: /usr/local/opt/readline/lib/libreadline.6.dylib
  Referenced from: /Users/pi/tmp/python-readline-test/.venv/lib/python3.5/readline.so
  Reason: image not found