我试图让我的脚本在用户按下返回键时触发用户输入。然后主程序将检查 txUpdated 标志并使用该输入。
我有一个在 python 中运行的线程,它只是等待用户输入:
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
问题是我不知道如何在不接收用户输入的情况下随时结束该线程。即使我的主程序设置了 endFlag,线程也不会结束,直到用户再输入一个输入。
有人对如何实现这一目标有任何建议吗?
这是一个仅限 Windows 的解决方案,基于这个答案亚历克斯·马尔泰利:
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
When endFlag
被设定为True
,线程将退出。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)