OS-X terminal behaves oddly after running Python interactively

After running a python repl (2.7.10) in the os-x terminal and exiting, the terminal no longer echos typed input and some other strange things happen. If I run python again and exit(), then the terminal seems to be restored. I now just close the tab and open a new one, so I havent tested that extensively.

I guess this is related to terminal settings, but its is a recent thing and I haven't changed anything that I recall. Python is installed with macports, if there is something to do with mis-matched dependencies with some console library. 2.7.10 was installed a while ago, and this didn't happen after installation.

Cracks knuckles and opens terminal

[~]: virtualenv-2.7 venv-test
[~]: source venv-test/bin/activate
[~]: python
>>> ^D>>>       *(press ctrl-d, the 2nd >>> is strange)
[~]:            *(type something like `ls-l`, nothing shows on console)
[~]: -bash: ls-l: command not found`

Additionally, running python again and hitting ctrl-d results in this output:

>>> ^D           (ctrl-d, then hit enter, doesn't exit)
>>> ^D           (...)
>>> ^D           (...)
>>> exit()       (typing exit() quits the session)
>>> [~]: 

There is an open bug in MacPorts on this issue:

https://trac.macports.org/ticket/48807

It says that installing python with the "+readline" option fixes the problem, which I verified by doing it myself.

sudo port uninstall python27
sudo port install python27 +readline

The terminal modes are set by your application to raw or cbreak, and when exiting abnormally the modes are not restored. In particular, the feature that maps the Enter key (control/M aka carriage return) to newline (control/J aka line feed) is often disabled in this case. You can fix the problem with returns by entering

stty sane

followed by controlJ

That will at least let you enter commands again, though the editing characters such as backspace may not be assigned to their usual functions.

Some may also advise using the reset command, but the given symptoms are not relevant to what that program does.

For further reading

  • Salvage a borked terminal
  • stty(1), interestingly though OSX is "BSD", its stty manual page is GNU
  • reset(1), from ncurses