一些在后台运行的任务,需要在特定条件下对用户发起通知,如果有跨端要求,可以用第三方库,不过需要付费,优势在于可同时兼容移动端和桌面端,这里只是个人使用,所以推荐使用Mac自带Apple Script来添加,本来考虑通过向Reminders
添加Event
的方式,实现Mack & iOS同时提醒,不过只找到OC和Swift的API,没找到Py的API
Notification
display notification
The AppleScript command:
1 | display notification "hello world!" with title "Greeting" subtitle "More text" |
With osascript:
1 | osascript -e 'display notification "hello world!" with title "Greeting" subtitle "More text"' |
make sound
The AppleScript command:
1 | display notification "hello world!" with title "Greeting" subtitle "More text" sound name "Submarine" |
executed by osascript:
1 | osascript -e 'display notification "hello world!" with title "Greeting" subtitle "More text" sound name "Submarine"' |
If the name of the sound is incorrect Mac will make an alert sound.
The sound can be one of the files in /System/Library/Sounds or in ~/Library/Sounds.
Code in Py 1
1 | import os |
此示例没有转义引号、双引号或其他特殊字符,因此这些字符将无法在通知的文本或标题中正确工作
update:这应该适用于任何字符串,不需要转义任何内容。它的工作原理是将原始字符串作为参数传递给apple脚本,而不是试图将它们嵌入到apple脚本程序的文本中。
1 | import subprocess |
Code Demo 2
1 | import os |
display alert
display alert with confirmation request
the AppleScript command:
1 | display alert "Hello World!" message "longer text can be added in the message field and it will be all shown on the pop-up alert." |
The osascript wrapped command:
1 | osascript -e 'display alert "Hello World!" message "longer text can be added in the message field and it will be all shown on the pop-up alert."' |
Saying
Saying Hello World
The AppleScript command:
1 | say "Hello World!" |
wrapped in osascript on the command line:
1 | osascript -e 'say "Hello World!"' |