Search code examples
pythonraw-input

if statement including raw_input just prints whatever i type in to the keyboard


I am very new to python and programming in general and I want to print out the string "forward" whenever i press "w" on the keyboard. It is a test which I will transform into a remote control for a motorized vehicle.

while True:
    if raw_input("") == "w":
        print "forward"

Why does it just print out every key I type?


Solution

  • In Python 2.x the raw_input function will display all characters pressed, and return upon receiving a newline. If you want different behaviour you'll have to use a different function. Here's a portable version of getch for Python, it will return every key press:

    # Copied from: stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user
    def _find_getch():
        try:
            import termios
        except ImportError:
            # Non-POSIX. Return msvcrt's (Windows') getch.
            import msvcrt
            return msvcrt.getch
    
        # POSIX system. Create and return a getch that manipulates the tty.
        import sys, tty
        def _getch():
            fd = sys.stdin.fileno()
            old_settings = termios.tcgetattr(fd)
            try:
                tty.setraw(fd)
                ch = sys.stdin.read(1)
            finally:
                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
            return ch
    
        return _getch
    
    getch = _find_getch()
    

    It can be used like so:

    while True:
        if getch() == "w":
            print "forward"