After digging around in SO for a while, I still haven\'t found a good answer to what I would hope is a fairly common need. Basically I need a main thread to do \"stuff\" unt
You created a thread but forget to start it:
listener = threading.Thread(target=kbdListener)
listener.start()
I found the accepted answer didn't work for me - it would still block at raw_input even in a separate thread. However, when I switched the threads around it worked right away.
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
In addition to MydKnight's answer (starting the thread), you need to change rawInput
to raw_input
, and it needs to be in some sort of while
loop otherwise you'll only get one raw_input()
logged.
If you actually want to keep the while
loop going on forever, you will need to create a new thread and start it, each time the old one has finished.
I updated the example in the question to make that work:
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)