在SO中挖掘了一段时间后,我仍然没有找到一个很好的答案,我希望这是一个相当普遍的需求。基本上我需要一个主线程来做“东西”直到它接收输入,然后对该输入进行操作,然后返回到原始的“东西”。每次我的问题似乎是我的程序执行似乎完全停止在原始输入,无论我是在一个线程或其他任何地方调用它。 Forwarning我是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)
答案 0 :(得分:2)
您创建了一个帖子但忘了启动它:
SELECT
T1.Description, T1.TYPE, T1.SALESPOTENTIAL , T2.STARTDATE,
T3.PROJECT_REGION, T3.JOB_TYPE
FROM
sysdba.OPPORTUNITY T1,
SELECT T1.TYPE, count(*)
FROM OPPORTUNITY
GROUP BY by TYPE,
JOIN
sysdba.ACTIVITY T2 ON T1.ACCOUNTID = T2.ACCOUNTID
JOIN
sysdba.C_OPPORTUNITY_EXT T3 ON T1.OPPORTUNITYID = T3.OPPORTUNITYID
WHERE
CLOSEPROBABILITY > 70
答案 1 :(得分:1)
除了MydKnight的回答(启动主题)之外,您需要将rawInput
更改为raw_input
,并且它需要处于某种while
循环中,否则您只会记录一个raw_input()
。
答案 2 :(得分:1)
如果你真的希望永远保持while
循环,你需要创建一个新的线程并在每次旧的线程完成时启动它。
我更新了问题中的示例以使其成功:
import threading
import time
kbdInput = ''
playingID = ''
finished = True
def kbdListener():
global kbdInput, finished
kbdInput = raw_input("> ")
print "maybe updating...the kbdInput variable is: {}".format(kbdInput)
finished = True
while True:
print "kbdInput: {}".format(kbdInput)
print "playingID: {}".format(playingID)
if playingID != kbdInput:
print "Received new keyboard Input. Setting playing ID to keyboard input value"
playingID = kbdInput
else:
print "No input from keyboard detected. Sleeping 2 seconds"
if finished:
finished = False
listener = threading.Thread(target=kbdListener)
listener.start()
time.sleep(2)
答案 3 :(得分:0)
我发现接受的答案对我来说并不起作用 - 即使在一个单独的线程中它仍然会阻止raw_input。然而,当我切换它周围的线程时,它立即工作。
import threading
def mainWork():
while 1:
#whatever you wanted to do until an input is received
myThread = threading.Thread(target=mainWork)
myThread.start()
while 1:
input = raw_input()
#do stuff with input when it is received