我正在使用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:
语句中通过以下方式调用:
错误处理如下:
except (KeyboardInterrupt, SystemExit):
os.system('clear')
print ('ctrl+C pressed. \nProgramme complete')
dB.commit()
dB.close()
screen.lcd_cleanup()
GPIO.cleanup()
一种常见的方法是创建一个全局变量,例如
pendingExit = False
,并在except
处理程序中将其设置为True
,然后join
工作线程等待其结束。在getVars
中的工作线程必须定期检查pendingExit
并结束。在相关问题 更多 >
编程相关推荐