这是一个仅限Windows的解决方案,基于Alex Martelli的
this answer:
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']:
return ''.join(result).rstrip()
if endFlag:
return None
time.sleep(0.1) # just to yield to other processes/threads
当endFlag设置为True时,线程将退出.