Standard keys functions in curses module

戏子无情 提交于 2019-12-06 01:59:26

Here is an example that allows you to keep backspace (keep in mind ASCII code for backspace is 127):

import curses
import time

window = curses.initscr()

curses.cbreak()
window.nodelay(True)
# Uncomment if you don't want to see the character you enter
# curses.noecho()
while True:
    key = window.getch()
    try:
        if key not in [-1, 127]:
           print key
    except KeyboardInterrupt:
        curses.echo()
        curses.nocbreak() # Reset the program, so the prompt isn't messed up afterwards
        curses.endwin()
        raise SystemExit
    finally:
        try:
            time.sleep(0.01)
        except KeyboardInterrupt:
            curses.echo()
            curses.nocbreak() # Reset the program, so the prompt isn't messed up afterwards
            curses.endwin()
            raise SystemExit
        finally:
            pass

The key not in [-1, 127] ignores printing 127 (ASCII DEL), or -1 (error). You can add other items into this, for other character codes.

The try/except/finally is for handling Ctrl-C. This resets the terminal so you don't get weird prompt output ater running.
Here is a link to the official Python docs, for future reference:
https://docs.python.org/2.7/library/curses.html#module-curses

I hope this helps.

the code in stackoverflow.com/a/58886107/9028532 allows you to use any keycodes easily!
https://stackoverflow.com/a/58886107/9028532

It demonstates that it does not ignore neither standard ENTER, Backspace nor Arrows keys. getch() works properly. But maybe the operating system catches some keys before getch() gets a chance himself. This usually is configurable to some extent in the operating system.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!