Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

python - How do I accept input from arrow keys, or accept directional input?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

import curses

screen = curses.initscr()
screen.addstr("Hello World!!!")
screen.refresh()
screen.getch()
curses.endwin()

Now open a terminal (not IDLE! a real terminal!) and run it via:

python test_curses.py

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...