I have 3 active Threads. One of them activa other Thread and uses getch () to detect the ESC key, if pressed the program closes.
When the other two Threads finish their operations (without pressing ESC) they close successfully but the first Thread still waits for ESC to be pressed. The programme is therefore still running.
class tracking():
def __init__(self):
self.tecla = '\x1b' #ESC
self.case = None
def pressed(self, case):
self.case = getch()
def inicio(self): #The Thread in question calls this function
Thread(target=self.pressed(self.case)).start()
while True:
if self.case is not None:
if self.case == self.tecla:
sys.exit()
else:
self.case = None
self.pressed(self.case)
That's because getch()
is synchronous. There are a few options:
You can select
to wait for an I/O operation (including the keyboard), see here: https://docs.python.org/2/library/select.html
You can use a library that allows you to detect key presses and then loop and wait until you get one. This could be cumbersome if you use something like, say, pygame .
You can break the thread yourself by using thread.interrupt_main , see here: https://docs.python.org/2/library/thread.html#thread.interrupt_main