Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Curses - Detecting the Backspace Key

I'm having a difficult time with detecting the Backspace key using the Curses module. Whenever I press the Backspace key, the character / string returned is '^?', however I'm not able to detect it with:

if str(key) == '^?':

The code below is set up to run

import curses

def main(win):
    win.nodelay(True)
    key = ''
    record = ''
    win.clear()
    win.addstr("Key:")
    win.addstr('\n\nRecord:')
    win.addstr(record)
    while True:
        try:
            key = win.getkey()

            if str(key) == '^?':
                # Attempt at detecting the Backspace key
                record = record[:-1]

            elif str(key) == '\n':
                # Attempt at detecting the Enter Key
                record = ''

            else:
                record += str(key)
            win.clear()
            win.addstr("Key:")
            win.addstr(str(key))
            win.addstr('\n\nRecord:')
            win.addstr(record)
            if key == os.linesep:
                break
        except Exception as e:
            # No input
            pass

curses.wrapper(main)
# CTRL+C to close the program
like image 841
Neil Graham Avatar asked Nov 25 '17 01:11

Neil Graham


People also ask

Can you use backspace in Python?

Backspace Character (\b): When you use backspace using keyboard it erases characters & space both, while when you use backspace in python it only erases space & shift string.

What are curses in Python?

What is curses? ¶ The curses library supplies a terminal-independent screen-painting and keyboard-handling facility for text-based terminals; such terminals include VT100s, the Linux console, and the simulated terminal provided by various programs.


1 Answers

According to your clarifying comment, backspace in your terminal is neither 'KEY_BACKSPACE' nor '\b' ('\x08').

Since you're using curses.wrapper(), which calls curses.initscr(), this suggests that something is wrong with either your terminfo database (unlikely) or your terminal configuration (more likely).

getkey() == 'KEY_BACKSPACE' or getch() == curses.KEY_BACKSPACE is supposed to work on any properly-configured system, so you're likely to have problems in other applications too.

The TERM environment variable is how the terminal type is communicated to tools which need the functionality beyond basic teletype, so, to fix that, start by checking what the TERM environment variable contains in the environment where you're running Python.

print(os.environ['TERM'])

As a quick hack, you can check all the values it's been observed to take.

if key in ('KEY_BACKSPACE', '\b', '\x7f'):
like image 103
ssokolow Avatar answered Oct 03 '22 12:10

ssokolow