[英]Stopping subprocess executing in a class
I'm trying to play a series of Audio files through MPlayer which is classed as a subprocess in Python. 我正在尝试通过MPlayer播放一系列音频文件,该文件被归类为Python中的子进程。
Then when the .stop() command is called. 然后在调用.stop()命令时。 I want the subprocess to..... well.. stop executing.
我希望子流程........停止执行。
The important thing I want to keep occurring is the main thread. 我想继续发生的重要事情是主线程。 I don't want Python to terminate altogether.
我不希望Python完全终止。
Below is the code I have tried out so far. 下面是到目前为止我尝试过的代码。
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()
However when I run this, I get an error saying alarmpi is not defined. 但是,当我运行此命令时,出现一条错误消息,提示未定义alarmpi。
Is there a different way to tackle this issue? 有解决此问题的其他方法吗?
Thanks in advance. 提前致谢。
just define alarmpi
as a member of the class using self
object to store it so you can recall it in the stop
method (define it first in the class constructor so you can call stop
without calling play
first) 只需使用
self
对象将alarmpi
定义为类的成员即可存储它,以便您可以在stop
方法中对其进行调用(在类构造函数中先对其进行定义,这样就可以在不先调用play
情况下调用stop
)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.