【发布时间】:2017-05-12 23:19:36
【问题描述】:
我正在尝试编写一个显示 macOS 警报并同时启动警报的 python 脚本。
警报关闭后应该停止警报声,但事实并非如此。
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")
上面的代码应该在开始循环警报声后显示一个 macOS 警报(在文件 beep.wav 中)。警报关闭后,警报声应立即停止。
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
【问题讨论】:
-
if process is not None:=>if process:。不要和is比较。 -
我宁愿创建一个线程来播放声音,而不是使用
subprocess在 shell 中循环在后台运行......对我来说听起来很脆弱。 -
@Jean-FrançoisFabre 我刚刚实施了该建议 (
if process:),但脚本仍然以同样的方式失败。 -
@Jean-FrançoisFabre 如果您告诉我如何在使用多线程后完成我的工作,我将不胜感激!我很想能够那样做,但不觉得我目前拥有自己做这件事的专业知识。我昨天花了大约 6 个小时试图找出如何从纯 python 中播放声音。
-
我会尝试
os.kill(process.pid,signal.SIGTERM)并删除os.killpg电话。我无法测试,我正在使用 windows
标签: python bash macos applescript subprocess