はじめに
Pythonで実行に数時間以上かかるプログラムを走らせて放置したり外出したりすることが多いのですが、そんなときにプログラムの終了通知やその他メッセージをiPhoneで受け取りたいと思い、Mac/iOSのリマインダーを使うことを考えました。
やっていること
以下にサンプルスクリプトとしてreminders.py
を作成しました。やっていることは単純で、MacのReminders.appに新規リマインダーを登録させるAppleScriptを、Pythonで作成・実行させているだけです。
-
script_org
でAppleScriptの文字列を定義する - 諸々の変数(タイトル, 本文, 通知時間の遅延)を文字列に突っ込む
-
subprocess.Popen()
で、完成したAppleScriptの文字列を標準入力としてshell上でosascript
を実行 - Reminders.appに新規リマインダーが登録され、指定時間にMac/iPhoneの両方で通知を表示してくれる
使用上の注意
実際に使用するときは、モジュールとしてインポートするのが良さそうです。また、使用前にはReminders.appでPython Notification
というリストを作成しておく必要があります。これはリマインダーの登録先となり、script_org
に記述したset pylist to
の後の文字列で定義しています。
example_of_usage
import reminders
reminders.notify(title='Python Notification',message='Calculation finished!',delay=0.25)
- title: リマインダーのタイトル(大きく表示される)
- message: リマインダーの本文(小さく表示される)
- delay: リマインダーを登録してから何分後に通知を出すか
サンプルスクリプト
reminders.py
# coding:utf-8
from subprocess import Popen, PIPE
script_org = \
'''
on run argv
set pylist to "Python Notification"
tell application "Reminders"
set notification to make new reminder in list pylist
set name of notification to "{0}"
set body of notification to "{1}"
set remind me date of notification to (current date) + ({2} * minutes)
end tell
end run
'''
def notify(title='Python Notification', message='Calculation finished!', delay=0.25):
script_send = script_org.format(title, message, delay)
command = Popen(['osascript'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
command.communicate(script_send)
if __name__ == '__main__':
notify()