Seeing escape characters when pressing the arrow keys in python shell
In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.
But after I ssh into another machine and start python
there, I get sessions like:
>>> import os
>>> ^[[A
where the last character comes from arrow-up. Or, using arrow-left:
>>> impor^[[D
How can I fix this?
In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.
I've solved this issue by installing readline
package:
pip install readline
On OS X, I have different problem.
When I using system python shell, the keys is no problem, but problem in virtualenv. I'd try to reinstall/upgrade virtualenv/readline and nothing fixed.
While I try to import readline
in problem python shell, get this error message:
ImportError: dlopen(/Users/raptor/.virtualenvs/bottle/lib/python2.7/lib-dynload/readline.so, 2): Library not loaded: /usr/local/opt/readline/lib/libreadline.6.dylib
Referenced from: /Users/raptor/.virtualenvs/bottle/lib/python2.7/lib-dynload/readline.so
Reason: image not found
Cause there is /usr/local/opt/readline/lib/libreadline.7.dylib
but not libreadline.6.dylib
, so I make a symbol link:
ln -s libreadline.7.dylib libreadline.6.dylib
Problem has been solved!
On OS X, Xcode updates sometimes break readline
. Solution:
brew uninstall readline
brew upgrade python3
brew install readline
pip3 install readline
If the problem still persists, try to remove readline
using pip
and install it using easy_install
:
pip3 uninstall readline
easy_install readline
Looks like readline is not enabled. Check if PYTHONSTARTUP
variable is defined, for me it points to /etc/pythonstart
and that file is executed by the python process before going interactive, which setups readline/history handling.
Thanks to @chown here is the docs on this: http://docs.python.org/2/tutorial/interactive.html
On OS X, using python 3.5 and virtualenv
$ pip install gnureadline
In the interpreter do:
import gnureadline
Now arrow keys should work properly.
Additional information...
Note that as of Oct 1, 2015 - readline has been DEPRECATED (source https://github.com/ludwigschwardt/python-readline)
Use gnureadline instead (see: https://github.com/ludwigschwardt/python-gnureadline)
If I install readline instead of gnureadline using python 3.5, I receive errors after attempt to import in the interpreter:
>>> 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