macOSアラートを表示して同時にアラームを開始するpythonスクリプトを作成しようとしています。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
'プロセスがNoneでない場合:' => 'の場合プロセス: '。 'is 'と比較しないでください。 –
私はむしろバックグラウンドで実行するシェルのループで 'サブプロセス 'を使用する代わりにサウンドを再生するスレッドを作成したいです...私には壊れやすい音。 –
@ Jean-FrançoisFabre私はその提案( 'if process:')を実装しましたが、スクリプトは引き続き同じ方法で失敗します。 – theonlygusti