2

我有一个 python 脚本,我在其中使用线程来等待我的树莓派上的输入。这是我第一次使用线程,我在处理键盘中断时遇到了一些困难。这不是一个真正的问题,但如果用户提前按下 control-c,就像程序一启动,python 就会吓坏并喷出一个充满导入错误的控制台。我尝试将导入包装在 try - excepts 中,但这似乎不起作用。我感觉它与线程有关,因为我以前从未遇到过这个问题。

除了将所有内容包装在 try-excepts 中,我还尝试了:

from threading import Thread
cond = threading.Condition(threading.Lock())
cond.acquire()
cond.wait(None)

我听说在加载之前不允许键盘中断?

反正有没有让python在键盘中断上做任何事情?

任何帮助,将不胜感激。谢谢!

我的代码:

import RPi.GPIO as GPIO
import pymysql as mysql
import time
import urllib.request
from threading import Thread

GPIO.setmode(GPIO.BOARD)
GPIO.cleanup()

class table():
    __slots__ = ['pin','num','time']

    def __init__(self, pin, num, time=0):
        self.pin = pin
        self.num = num
        self.time = time

# Room ID
room = 6

# time (minutes)
thetime = 38

# table Setup
tableList = [ \
    table(11,6), \
    table(13,2), \
    table(15,4), \
    table(19,5), \
    table(21,3), \
    table(23,1), \
    ]

def settable(table):
    with urllib.request.urlopen("http://time.zyphox.com") as url:
        curtime = int(url.read())+(thetime*60)

    con = mysql.connect(host="345", user="435", passwd="345435", db="34534543")
    cur = con.cursor()
    cur.execute("UPDATE tables SET time='"+str(curtime)+"' WHERE number='"+str(table)+"' AND id_room='"+str(room)+"'")
    cur.close()
    con.close()
    print("Setting table " + str(table) + " to " + str(thetime) + " minutes...")

def watchtable(table):
    GPIO.setup(table.pin, GPIO.IN)  
    while True:
        if(GPIO.input(table.pin)!=1 and table.time <= time.time()):
            settable(table.num)
            table.time = time.time() + 10

def main():
    print("Loading kitchen System...")
    for table in tableList:
            t = Thread(target=watchtable,args=(table,))
            t.daemon=True
            t.start()
    time.sleep(1)
    print("Successful!")

    while True:
        time.sleep(300)
        print("- Pinging MYSQL database.")

main()
4

0 回答 0