Reputation: 5
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?
Upvotes: 0
Views: 74
Reputation: 280236
raw_input
reads an entire line of input. The line you're inputting is made visible to you, and you can do things like type some text:
aiplanes
go left a few characters to fix your typo:
airplanes
go back to the end and delete a character because you didn't mean to make it plural:
airplane
and then hit Enter, and raw_input
will return "airplane"
. It doesn't just return immediately when you hit a keyboard key.
If you want to read individual keys, you'll need to use lower-level terminal control routines to take input. On Unix, the curses
module would be an appropriate tool; I'm not sure what you'd use on Windows. I haven't done this before, but on Unix, I think you'd need to set the terminal to raw or cbreak mode and take input with window.getkey()
or window.getch()
. You might also have to turn off echoing with curses.noecho()
; I'm not sure whether that's included in raw/cbreak mode.
Upvotes: 1
Reputation: 534
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"
Upvotes: 2