我試圖循環報警(文件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