我想寫一個python腳本,它顯示macOS警報並同時啓動警報。關閉macOS警報後,子進程沒有中斷
警報關閉後應該停止警報聲,但事實並非如此。
def show_alert(message="Flashlight alarm"):
"""Display a macOS dialog."""
message = json.dumps(str(message))
exit_status = os.system("osascript dialog.scpt {0}".format(message))
return exist_status
def play_alarm(file_name = "beep.wav", repeat=3):
"""Repeat the sound specified to mimic an alarm."""
process = subprocess.Popen(['sh', '-c', 'while :; do afplay "$1"; done', '_', file_name], shell=False)
return process
def alert_after_timeout(timeout, message, sound = True):
"""After timeout seconds, show an alert and play the alarm sound."""
time.sleep(timeout)
process = None
if sound:
process = play_alarm()
exit_status = show_alert(message)
if process is not None:
os.killpg(os.getpgid(process.pid), signal.SIGINT)
process.kill()
# also, this below line doesn't seem to open an alert.
show_alert(exit_status)
alert_after_timeout(1, "1s alarm")
上述代碼應開始循環的報警聲(文件beep.wav
中)後顯示的MacOS警報。當警報關閉時,警報聲應立即停止。
的AppleScript的文件dialog.scpt
觸發警報,只有幾行:
on run argv
tell application "System Events" to display dialog (item 1 of argv) with icon file (path of container of (path to me) & "Icon.png")
end run
'如果過程不無:'=>'如果過程:'。不要與'is'比較。 –
我寧願創建一個線程來播放聲音,而不是使用'subprocess'與shell中的循環在後臺運行......聽起來對我來說很脆弱。 –
@ Jean-FrançoisFabre我剛剛實現了這個建議('if process:'),但腳本仍然以相同的方式失敗。 – theonlygusti