Reputation: 653
I'm trying to read from a thread in python as follows
import threading, time, random
var = True
class MyThread(threading.Thread):
def set_name(self, name):
self.name = name
def run(self):
global var
while var == True:
print "In mythread " + self.name
time.sleep(random.randint(2,5))
class MyReader(threading.Thread):
def run(self):
global var
while var == True:
input = raw_input("Quit?")
if input == "q":
var = False
t1 = MyThread()
t1.set_name("One")
t2 = MyReader()
t1.start()
t2.start()
However, if I enter 'q', I see the following error.
In mythread One
Quit?q
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 522, in __bootstrap_inner
self.run()
File "test.py", line 20, in run
input = raw_input("Quit?")
EOFError
In mythread One
In mythread One
How does on get user input from a thread?
Upvotes: 0
Views: 1638
Reputation: 1941
Your code is a bit strange. If you are using the reader strictly to quit the program, why not have it outside the threading code entirely? It doesn't need to be in the thread, for your purposes, and won't work in the thread.
Regardless, I don't think you want to take this road. Consider this problem: multiple threads stop to ask for input simultaneously, and the user types input. To which thread should it go? I would advise restructuring the code to avoid this need.
Upvotes: 1