Python:从后台进程启动后台进程

2024-05-18 06:12:53 发布

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

我有一点问题,我的许多测试/搜索到目前为止都没有给我带来任何结果。在

我有一个烧瓶应用程序,它为运行在树莓派上的小型报警系统提供了一个图形用户界面。 GUI允许启动警报(目前GPIO引脚上的运动传感器)作为后台进程。这运行得很好,如果检测到它会发送一封电子邮件。 我正在尝试添加一个方法,将播放警报声(或黑色金属歌曲在100分贝,还没有决定:p)。 方法本身在一个类中,工作正常,我可以从GUI中将它作为另一个后台进程来激活/停用。在

但是,我不能让它自动触发报警过程。不知道为什么,我没有错误,它只是不发射:

class Alarm(Process):

  def __init__(self):
      super().__init__()
      self.exit = Event()


  def shutdown(self):
      self.exit.set()

  def run(self):

      Process.__init__(self)

      #code
      #if motion detected sendmail, and run the siren:

      siren = Siren()  #actually, problem here: I need to import the class 
                       #and declare this in the main Flask app file, so as 
                       #to be able to control it from the GUI. Apparently I 
                       #can't declare it in both python files (sounds 
                       #obvious though)
      siren.start()

      #then keep looping

而塞壬的等级是相似的:

^{pr2}$

我猜我对类和方法的基本理解是罪魁祸首。 我也尝试过使用events,所以我将使用类似于e = Event()和{}之类的东西来代替siren.start(),但是我无法在后台运行Siren类并让它用e.wait()来拾取事件。在

有人能给我指出正确的方向吗?在

谢谢!在


Tags: theto方法selfevent报警进程init
1条回答
网友
1楼 · 发布于 2024-05-18 06:12:53

您不应该从Alarm.run调用Process.__init__!{cd3>你已经在做了

Process.__init__(self)与{}完全相同

更新

这有助于:

import threading
import time

class Alarm(threading.Thread):



    def run(self):

        #code
        #if motion detected sendmail, and run the siren:

        siren = Siren()  #actually, problem here: I need to import the class 
                         #and declare this in the main Flask app file, so as 
                         #to be able to control it from the GUI. Apparently I 
                         #can't declare it in both python files (sounds 
                         #obvious though)
        siren.start()


        #then keep looping
        for x in range(20):
            print ".",
            time.sleep(1)
        siren.term()
        siren.join()



class Siren(threading.Thread):

    def run(self):

        self.keepRunning=True;

        while self.keepRunning:
            print "+",
            time.sleep(1)

    def term(self):
        self.keepRunning=False

if __name__ == '__main__':
    alarm = Alarm()
    alarm.run()

输出:

^{pr2}$

相关问题 更多 >