在键盘break exi上干净地停止python线程

2024-04-20 11:54:14 发布

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

我正在使用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:语句中通过以下方式调用:

^{pr2}$

错误处理如下:

except (KeyboardInterrupt, SystemExit):
    os.system('clear')
    print ('ctrl+C pressed. \nProgramme complete')
    dB.commit()
    dB.close()
    screen.lcd_cleanup()
    GPIO.cleanup()

Tags: to数据库fielddbsqlif线程global