繁体   English   中英

干净地停止键盘中断出口上的python线程

[英]Cleanly stop a python thread on keyboard break exit

我正在使用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()

一种常用的方法是创建一个全局变量,例如, pendingExit = False并在except处理程序中将其设置为True ,然后join工作线程以等待其结束。

然后, getVars的工作线程必须定期检查pendingExit并结束。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM