python 暂停程序 等待用户输入,Python:停止正在等待用户输入的线程

I'm trying to have my script trigger a user input when the user pressed the return key. The main program will then check the txUpdated flag and use this input.

I have a thread running in python that simply waits for user input:

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

The problem is I don't know how to end this thread at any point without receiving a user input. Even if my main program sets the endFlag the thread wont end until the user inputs one more input.

Does anyone have any suggestions on how to accomplish this?

解决方案

Here is a Windows-only solution, based on this answer by Alex Martelli:

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 is set to True, the thread will exit.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值