我试图循环报警(文件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()
宜'如果self.process'是一个'while not self.process:pass'来等待线程准备好被杀死? – theonlygusti
此解决方案仍然无法正常工作。 – theonlygusti
@theonlygusti - 我添加了一些锁以堵塞这些洞。它在我写的一些黑客测试中起作用。你可以在你的环境中测试吗? – tdelaney