Python: stop a thread waiting for user input

I am trying to have my script run user input when the user presses the return key. Then the main program checks the txUpdated flag and uses this input.

I have a thread running in python that just waits for user input:

class InputThread(threading.Thread): def __init__(self, threadID, name): threading.Thread.__init__(self) self.threadID = threadID self.name = name def run(self): global screenLock global txUpdated global txMessage global endFlag lock = threading.Lock() print "Starting " + self.name while not endFlag: txMessage = raw_input() if (txMessage == ""): screenLock = 1 txMessage = raw_input("Enter Tx String: ") screenLock = 0 with lock: txUpdated = 1 print "Exiting " + self.name 

The problem is that I do not know how to end this thread at any time without receiving user input. Even if my main program sets endFlag, the stream will end until the user enters another input.

Does anyone have any suggestions on how to do this?

+6
source share
1 answer

Here is a Windows solution based on this answer from Alex Martelli:

 import msvcrt import time import threading endFlag = False class InputThread(threading.Thread): def __init__(self, threadID, name): threading.Thread.__init__(self) self.threadID = threadID self.name = name def run(self): global screenLock global txUpdated global txMessage lock = threading.Lock() print "Starting " + self.name while not endFlag: txMessage = self.raw_input_with_cancel() # This can be cancelled by setting endFlag if (txMessage == ""): screenLock = 1 txMessage = raw_input("Enter Tx String: ") screenLock = 0 with lock: txUpdated = 1 print "Exiting " + self.name def raw_input_with_cancel(self, prompt=None): if prompt: print prompt, result = [] while True: if msvcrt.kbhit(): result.append(msvcrt.getche()) if result[-1] in ['\r', '\n']: print return ''.join(result).rstrip() if endFlag: return None time.sleep(0.1) # just to yield to other processes/threads 

If endFlag set to True , the stream will terminate.

+2
source

Source: https://habr.com/ru/post/973378/


All Articles