我对python和编程非常陌生,每当我在键盘上按"w“键时,我都想打印出字符串”前进“。这是一项测试,我将把它转变为机动车辆的遥控器。
while True:
if raw_input("") == "w":
print "forward"为什么它只打印出我输入的每一个键?
发布于 2016-04-08 23:05:50
在Python2.x中,raw_input函数将显示按下的所有字符,并在收到换行符后返回。如果你想要不同的行为,你必须使用不同的功能。下面是的可移植版本,它将返回每个按键:
# 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()它可以这样使用:
while True:
if getch() == "w":
print "forward"https://stackoverflow.com/questions/36510431
复制相似问题