我的覆盆子机器人需要一个简单的操纵杆。由于X-Server问题等原因,PyGame在我的IDE,eclipse或putty中无法正常工作。
为此,我想编写一个简约的键事件监听器,但我无法使用我的代码让python监听密钥释放事件:
import sys, tty, termios, time
#Old settings
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
#Loop
work=0
while True:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
if "w" in ch and work==0:
work=1
print "Car goes"
if "w" not in ch and work==1:
work=0
print "Car stops"
if ch in "c":
break
如果我按住键w,它将被识别。如果我释放它,循环将等待新的输入。
我的循环为什么以及在哪一行等待密钥关闭?我想用测试目的的简约代码来做这件事。
答案 0 :(得分:1)
您的代码停在
ch = sys.stdin.read(1)
因为它试图从stdin读取1个字符,但它没有,所以它只等到有一个字符。
如果你想以非阻塞方式读取它,请检查一下: https://repolinux.wordpress.com/2012/10/09/non-blocking-read-from-stdin-in-python/
正如您所看到的,有多种方法可以做到,但它们并不是很简单