我正在使用python线程来检查本地SQL数据库中的值是否有变化。我在主程序上有错误处理来处理Ctrl + C键盘中断。这会停止主代码但线程继续运行。当按下ctlr + c时,我应该如何干净地停止线程。谢谢。 线程是这样的:
def getVars():
global setTemp
global pidControl
while True:
dB = MySQLdb.connect(host="localhost",
user="pythonUser",
passwd="password123",
db="pythonProg")
cur = dB.cursor()
cur.execute("SELECT * FROM PiBQ_Temp WHERE tempKey = 1")
for field in cur:
fetchTemp = field[1]
print ("Thread getVars checked temp: " + fetchTemp)
# Check to see if fetchTemp is different to setTemp and update pid if needed
if fetchTemp != setTemp:
setTemp = fetchTemp
pidControl.setPoint(setTemp)
time.sleep(5)
它在主try:
语句中被调用:
# Start the getVars thread
t = threading.Thread(target=getVars, args=())
t.start()
print "Thread started: getVars"
错误处理是:
except (KeyboardInterrupt, SystemExit):
os.system('clear')
print ('ctrl+C pressed. \nProgramme complete')
dB.commit()
dB.close()
screen.lcd_cleanup()
GPIO.cleanup()
答案 0 :(得分:1)
一种通常的方法是创建一个全局变量,例如pendingExit = False
并将其设置为True
处理程序中的except
,然后join
工作线程等待其结束。
getVars
中的工作线程必须定期检查pendingExit
并结束。