5

I use the following trick in some of my Python scripts to drop into an interactive Python REPL session:

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

This usually works well on various RHEL machines at work, but on my laptop (OS X 10.11.4) it starts the REPL seemingly without readline support. You can see I get the ^[[A^C garbage characters.

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

If I call python directly, up arrow command history in the REPL works fine.

I tried inspecting globals() to look for some clues, but in each case they appear to be the same. Any ideas on how I can fix this, or where to look?

Edit: And to show the correct behavior:

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'
complex
  • 116
  • 4

2 Answers2

5

Just import readline, either in the script or at the console.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
  • Doing `import readline` does indeed give up arrow command history. That is helpful. However, why don't I have to import the deadline module when running "bare" `python`? – complex Apr 17 '16 at 13:01
  • I don't know. I don't think it's an issue with your installation. I have the exact same behaviour on OSX 10.10 and when I ssh into an Ubuntu machine. – Alex Hall Apr 17 '16 at 13:10
0

The program rlwrap solves this problem in general, not just for Python but also for other programs in need of this feature such as telnet. You can install it with brew install rlwrap if you have Homebrew (which you should) and then use it by inserting it at the beginning of a command, i.e. rlwrap python repl.py.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
  • Appreciate the pointer to rlwrap. However, I don't have Homebrew installed and don't plan on doing so (for reasons not relevant here). I'd to figure out how and why this doesn't work with the built-in `python`. – complex Apr 17 '16 at 12:54