【发布时间】:2017-05-15 13:59:14
【问题描述】:
我正在尝试循环警报(在文件 beep.wav 中)并显示警报。
警报关闭后,我想立即停止警报。
我正在尝试使用线程控制警报播放的解决方案。
但是,它会引发错误:
Traceback (most recent call last):
File "test.py", line 28, in <module>
thread.stop()
File "test.py", line 21, in stop
self.process.kill()
AttributeError: 'AlarmThread' object has no attribute 'process'
我真的不知道为什么会抛出这个错误,但看起来 self.process 出于某种原因在调用 AlarmThread.stop 时没有分配。
这对我来说毫无意义,因为从我的代码看来 thread.stop 仅在 thread.start 之后被调用:
import subprocess
import threading
class AlarmThread(threading.Thread):
def __init__(self, file_name="beep.wav"):
super(AlarmThread, self).__init__()
self.file_name = file_name
self.ongoing = None
def run(self):
self.ongoing = True
while self.ongoing:
self.process = subprocess.Popen(["afplay", self.file_name])
self.process.wait()
def stop(self):
if self.ongoing is not None:
self.ongoing = False
self.process.kill()
thread = AlarmThread()
thread.start()
# show_alert is synchronous, an alert must be closed before the script continues
show_alert("1 second timer")
thread.stop()
thread.join()
【问题讨论】:
标签: python multithreading macos subprocess python-2.x