Python:线程回调无法使用守护进程模式?

时间:2015-12-24 18:52:24

标签: python multithreading daemon

我是Python的新手。 我的一个线程回调代码在我的raspi上工作正常。

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
import time
from daemon import runner

GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)   # float switch goes down (closed to open) => low water level
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)     # float switch goes up (opened to close)  => high water level

def callback_lowlevel(channel):
    if GPIO.input(channel):
        print "Low water level in the sump detected"
    else:
        print "Water level in the sump returned to normal"

def callback_highlevel(channel):
    if GPIO.input(channel):
        print "High water level in the sump detected"
    else:
        print "Water level in the sump returned to normal"

GPIO.add_event_detect(23, GPIO.BOTH, callback=callback_lowlevel, bouncetime=1000)
GPIO.add_event_detect(24, GPIO.BOTH, callback=callback_highlevel, bouncetime=1000)

如果我开始这样的无限循环:

try:
    print "Waiting for events"
    while True:
        time.sleep(1)

except KeyboardInterrupt:
    GPIO.cleanup()       # clean up GPIO on CTRL+C exit
GPIO.cleanup()           # clean up GPIO on normal exit

有效。

但如果我" daemonize"它与守护进程库,我的线程回调不再工作。

class App():                           # Daemon content, not doing much, sleeping mostly, to lower CPU footprint
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/stdout'
        self.stderr_path = '/dev/stdout'
        self.pidfile_path =  '/var/run/aquamonitor.pid'
        self.pidfile_timeout = 5
    def run(self):
        Logger("Starting monitoring")
        while True:
            time.sleep(1)                           # Sleep most of time to be not too CPU intensive
app = App()                                         # Init the App
daemon_runner = runner.DaemonRunner(app)            # Run as a daemon
daemon_runner.do_action()                           # Just do it

我做错了什么?它作为守护进程的事实是否会改变我应该编写线程回调的方式?

1 个答案:

答案 0 :(得分:1)

我有同样的问题,我想我正在将回调注册到错误的线程。所以,简而言之,请确保在App类的run方法中调用GPIO.add_event_detect,就在循环之前。

相关问题