Python干净的键盘中断

时间:2013-04-19 05:21:33

标签: python multithreading keyboardinterrupt

我有一个python脚本,我正在使用线程等待我的覆盆子pi上的输入。这是我以前第一次使用线程,我在处理KeyboardInterrupt时遇到了一些困难。它不是一个真正的问题,但如果用户提前按下control-c,就像程序启动时一样,python就会惊慌失措,并且会给控制台注入一系列导入错误。我试过在try-excepts中包装导入,但这似乎不起作用。我感觉它与线程有关,因为我之前从未遇到过这个问题。

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

from threading import Thread
cond = threading.Condition(threading.Lock())
cond.acquire()
cond.wait(None)
我听到的是假设在加载之前不允许键盘中断?

无论如何只是为了不让python在keyboardinterrupts上做任何事情?

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

我的代码:

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()

0 个答案:

没有答案