[ Read special keys in linux terminal without clearing screen ]
I have a program where I simply need to read special keys in a linux terminal (both xterm and console). Currently I am using the curses
to do it (though I absolutely do not need curses for anything else), and it works perfectly except for the one nuisance: I do not want curses to clear the screen and change the CRLF mode.
That is, this code would do it:
stdscr = curses.initscr()
curses.cbreak()
curses.noecho()
stdscr.keypad(1)
while True:
c = stdscr.getch()
if c == curses.KEY_UP:
scroll_up()
elif c == curses.KEY_DOWN:
scroll_down()
but the complication is that it will clear the screen and previous content on the terminal is not seen; also all output from background processes will have newlines converted to linefeed only.
I know I can turn the terminal into uncooked mode myself, delay after ESC
character, and so, but I want this program to work with special keys such as F1, Home and ↑ consistently, on all terminals, and as such it would be PITA
Thus is there any way to either
- Avoid clearing screen with curses and changing the newline mode (I read that the function
newterm
of ncurses could be used for it, but it is not implemented by Python), or - Any way to restore the original screen after it was cleared and manually restore the CRLF behavior and such, or
- Any other simple way of consistently reading special keys in Linux?
Answer 1
(Moved from the comments)
Maybe have a look at https://bitbucket.org/pypy/pyrepl
. It is curses-based but doesn't clear the screen. The applications pythoni
and pythoni1
give a Python prompt that doesn't use readline
, but present a similarish interface, with a few extras like multiline editing (in case we try to type a multiline command).
To answer your latest comment: the arrow keys work for me in pythoni
and pythoni1
...