4

Have a simple program:

import curses
import time

window = curses.initscr()

curses.cbreak()
window.nodelay(True)

while True:
    key = window.getch()
    if key != -1:
        print key
    time.sleep(0.01)


curses.endwin()

How can i turn on mode that doesn't ignore standart Enter, Backspace and Arrows keys functions? or only the way is to add all special characters to elif:

if event == curses.KEY_DOWN:
    #key down function

I'm trying modes curses.raw() and other, but there no effect... Please add example if you can.

mcklayin
  • 1,330
  • 10
  • 17
  • 1
    I'm not sure what you mean. Can you indicate in your code example what you want to achieve? – chtenb May 23 '14 at 17:56

2 Answers2

1

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.

ASCIIThenANSI
  • 865
  • 1
  • 9
  • 27
  • I hope it helped if you explained why that dual try–except cascade of yours is necessary but no " finally: curses.endwin() " …… Also: what point does "finally: pass" make at all? – dotbit Nov 16 '19 at 01:41
1

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.

dotbit
  • 4,445
  • 1
  • 7
  • 8