Python:停止等待用户inpu的线程

2024-09-29 19:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有人对如何做到这一点有什么建议吗?在


Tags: 用户nameselfinitdef线程globalthread
1条回答
网友
1楼 · 发布于 2024-09-29 19:22:25

以下是基于Alex Martelli的this answer的纯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

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

相关问题 更多 >

    热门问题