Python:停止等待用户输入的线程

时间:2014-08-05 16:04:22

标签: python multithreading

当用户按下返回键时,我正在尝试让脚本触发用户输入。然后主程序将检查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,线程也不会结束,直到用户再输入一个输入。

有没有人对如何做到这一点有任何建议?

1 个答案:

答案 0 :(得分:2)

以下是基于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']:
                    print
                    return ''.join(result).rstrip()
            if endFlag:
                return None
            time.sleep(0.1)  # just to yield to other processes/threads

endFlag设置为True时,线程将退出。