Search code examples
pythonlinuxraw-input

raw_input recognizes ^? but not ^H


I'm trying to get the backspace key to work in a python script that I have. Basically, the code in the script looks something like:

print("Please type the character 'h':")
choice = raw_input()
if choice == 'h':
        print("Thanks.")
else:
        print("You input the wrong character.")

Now, obviously, this is a toy script, but I'm having difficulty getting raw_input() to do what I want. For example, if I run the script, type a, then realize that I've typed the wrong character, and so hit backspace, I get:

Please type the character 'h':
a^H

But, if I type ^? instead, it translates to the correct command:

Please type the character 'h':
<<< CURSOR HERE

So, my question is this: I think this has to do with my linux environment - i.e. I think I need to load a keymap that tells linux that I want it to output ^? when the backspace key is hit, but I don't know why it seems to work in all other programs (even the python interpreter, surprisingly - if I manually put that code into the python interpreter, it works as expected!)


Solution

  • What terminal program are you using? It may have a setting with which you can control how your backspace key is interpreted.

    In gnome-terminal, if you click on Edit>Profile Preferences>Compatibility, you can tell gnome-terminal to send ASCII DEL instead of Ctrl-h when the backspace key is pressed. enter image description here


    Otherwise, I think you can fix your keymap with something like

    xmodmap -e "keycode 22 = BackSpace"
    

    My memory is rusty, however. Please consult the HOWTO and/or this guide for details.