所以我正在尝试编写一个程序来查找键盘按键,然后根据用户输入的内容在主程序中执行某些操作。我试图在一个线程中运行键盘,然后在主循环中比较变量中的什么,但我似乎没有得到线程键盘输入。在下面的代码中,打印可能更新行永远不会发生,只是来自主while循环的else块。我需要做什么才能使我的主循环知道用户按下的键?
import threading
import time
kbdInput = ''
playingID = ''
def kbdListener():
global kbdInput
kbdInput = rawInput()
print "maybe updating...the kbdInput variable is: ",kbdInput
listener = threading.Thread(target=kbdListener)
while True:
print "kbdInput: ",kbdInput
print "playingID: ",playingID
if playingID != kbdInput:
print "Recieved new keyboard Input. Setting playing ID to keyboard input value"
playingID = kbdInput
else:
print "No input from keyboard detected. Sleeping 2 seconds"
time.sleep(2)
答案 0 :(得分:0)
您需要在创建listener.start()
后调用listener
来启动监听器。
listener = threading.Thread(target=kbdListener)
listener.start()