小编Myd*_*ght的帖子

python中的非阻塞raw_input()

在SO中研究了一段时间之后,我仍然没有找到一个很好的答案,我希望这是一个相当普遍的需求。基本上,我需要一个主线程来执行“填充”,直到它接收到输入,然后对该输入进行操作,然后返回到原始的“填充”。每次我的问题似乎都是我的程序执行似乎完全在原始输入处停止,无论我是在线程中还是在其他任何地方调用它。警告我对python还是个新手,但我希望它不要太讨厌实现。这是我在玩的游戏(从我的其他问题中轻松回答了我的穿线问题)

因此,我正在尝试编写一个程序,该程序查找键盘按键,然后根据用户输入的内容在主程序中执行某些操作。我试图在一个线程中监听键盘,然后在主循环中比较变量中的内容,但是我似乎从未得到过线程键盘输入。在下面的代码中,可能永远不会发生打印更新行,而只是主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)
Run Code Online (Sandbox Code Playgroud)

python

6
推荐指数
1
解决办法
5259
查看次数

标签 统计

python ×1