This may be an xy problem, but I'm trying to to build a kernel based text editor, similar to vim
or nano
, and I know how to use the escape chars to clear the screen, then reprint, I can have it accept characters, but I'm not sure how to get it to accept arrow inputs for navigation. I thought there were ASCII values for them, but apparently not. Is there a way to use the arrows, or do I have to make a navigation mode and insert mode like vim
?
I've also briefly played with curses
, but that was prohibitive because, as I understood, a whole new window had to be opened for it and this is not compatible with the vision of a single terminal window that I had.
Edit: curses
was also prohibitive because it cleared the window, which I didn't want.
I know that I'm late to the party, but I really liked
click
package mentioned by @elbaschid. I don't know why he wasn't upvoted - maybe because his example doesn't show how to handle specifically cursor keys.Here is my $0.02 on that:
This handles cursor keys and as a bonus prints py-string representation of any keyboard shortcut it doesn't yet recognize. For example Ctrl-s is
"\x13"
. You can later use it inside anotherI've tried to add edit to @elbaschid answer but it was rejected ¯\_(ツ)_/¯. Please give him credit if you also like my answer
Awesome library for quick command-line prototyping.
curses
is exactly what you want. In fact I believe vim implements its interface with curses.Try to put the following code into a file called
test_curses.py
:Now open a terminal (not IDLE! a real terminal!) and run it via:
You should see that the terminal was cleared and an
Hello World!!!
writing appeared. Press any key and the program will stop, restoring the old terminal contents.Note that the
curses
library isn't as easy and "user-friendly" as you may be accustomed to. I suggest reading the tutorial (unfortunately for the C language, but the python interface is mostly the same)To Perform desired Action on Arrow key or Any other key as it pressed
The Python package
click
used for building commandline clients also comes with an implementation that allows you to get the key press events:It returns the key representation as Unicode character and "things like arrow keys will show up in the platform’s native escape format.".
This is the example taken straight from the click documentation on
getchar
:I wound up using the code from this question, and modifying the
__init__
statement so that it accepted up to 3 characters in a list.This allowed me to get arrow keys as well as all other characters and escape sequences from the keyboard for the editor. It made the "Getch" class not strictly a
get char
clone because it returns a string, but it wound up being much more useful.