首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python :从后台进程开始后台进程

Python :从后台进程开始后台进程
EN

Stack Overflow用户
提问于 2017-09-22 05:03:29
回答 1查看 438关注 0票数 0

我遇到了一些问题,我的许多测试/搜索到目前为止并没有给我带来任何帮助。

我有一个水瓶应用程序,为一个小型警报系统提供一个GUI,运行在一个覆盆子上。GUI允许作为后台进程启动警报( GPIO引脚上的运动传感器)。这运行良好,如果检测到,它会发送电子邮件。我正在尝试添加一个方法来播放警笛的声音(或者是一首100分贝的黑色金属歌曲,还没有决定:p )。方法本身在一个类中,工作正常,我可以从GUI激活/停用它作为另一个后台进程。

但是,我无法通过报警过程自动触发它。不知道为什么,我没有错,只是没有触发:

代码语言:javascript
复制
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

而警报器的等级也是相似的:

代码语言:javascript
复制
class Siren(Process):
    def __init__(self):
        super().__init__()

    def run(self):

        Process.__init__(self)

        #code using pyaudio

我猜我对类和方法的基本理解就是罪魁祸首。我也尝试过使用事件,所以我不会使用siren.start(),而是e = Event()e.set(),但是我无法在后台运行Siren类,并让它用e.wait()来获取该事件。

有人能为我指明正确的方向吗?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-22 05:20:17

您不应该从Process.__init__调用Alarm.run!您已经在Alarm.__init__中这样做了。

Process.__init__(self)super().__init__()完全相同

更新

这是否有帮助:

代码语言:javascript
复制
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()

产出:

代码语言:javascript
复制
+. + . .+ . + +. +. . + . + . + . + + . + . + . + . + . + . + . + . +. +. +
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46357182

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档