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

7

我希望我的脚本在用户按下回车键时触发用户输入。然后主程序将检查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,线程也不会结束,直到用户再次输入一条消息。
有人有什么建议吗?

你需要支持哪些平台? - dano
这只是在cmd.exe中运行的脚本。所以我猜只能在Windows上运行。 - spizzak
1个回答

2

以下是基于Alex Martelli的这个答案的Windows-only解决方案:

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 时,线程将会退出。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接