我想写一个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