Search code examples
pythonmultithreadinggetch

How to abort gech () in python?


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)

Solution

  • That's because getch() is synchronous. There are a few options: