停止在类中执行子进程

时间:2017-01-28 11:25:28

标签: python python-3.x raspberry-pi mplayer

我正在尝试通过MPlayer播放一系列音频文件,这被归类为Python中的子进程。

然后调用.stop()命令。我希望子流程能够......停止执行。

我想要继续发生的重要事情是主线程。我不希望Python完全终止。

以下是我到目前为止尝试过的代码。

class Alarm:

    urllib.request.urlretrieve(Settings.news_url, 'news.mp3')

    tts1 = gTTS(text='Good morning' + Settings.name + 'It is ' + str(date.today()), lang='en')
    tts2 = gTTS(text='Here is the latest news from the BBC world service', lang='en')
    tts3 = gTTS(text='The weather for today is ' + Settings.weather_rss.entries[0]['title'].split(' ', 1)[1], lang='en')
    tts4 = gTTS(text='That is all for now. Have a great day!', lang='en')

    tts1.save(Settings.greeting)
    tts2.save(Settings.news_intro)
    tts3.save(Settings.weather_forecast)
    tts4.save(Settings.outtro)


    def play(self):     
        alarmpi = subprocess.call(['mplayer', Settings.greeting, Settings.news_intro, 'news.mp3', Settings.weather_forecast, Settings.outtro]);

    def stop(self):
        alarmpi.kill()

alarm = Alarm()

on = Thread(target=alarm.play)
stop = Thread(target=alarm.stop)
on.start()
time.sleep(5)
stop.start()

然而,当我运行这个时,我得到一个错误,说没有定义alarmpi。

有没有不同的方法来解决这个问题?

提前致谢。

1 个答案:

答案 0 :(得分:1)

只需将alarmpi定义为类的成员,使用self对象存储它,以便您可以在stop方法中调用它(首先定义它)在类构造函数中,这样您就可以在不先调用stop的情况下调用play

def __init__(self):
    self.alarmpi = None

def play(self):     
    self.alarmpi = subprocess.call(['mplayer', Settings.greeting, Settings.news_intro, 'news.mp3', Settings.weather_forecast, Settings.outtro]);

def stop(self):
    if self.alarmpi:
        self.alarmpi.kill()
        self.alarmpi = None