Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Up Arrow" history in Python on OS X and code.InteractiveConsole

Tags:

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'
like image 311
complex Avatar asked Apr 17 '16 12:04

complex


1 Answers

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

like image 91
Alex Hall Avatar answered Sep 28 '22 01:09

Alex Hall