There was a situation where I wanted to get Mac notifications from a Python script, so
--Execute AppleScript with a command --Execute the above command from Python
I created it in the flow.
In AppleScript
notification.scpt
display notification "Hello World"
You can view desktop notifications with. In the figure below, it is executed from ScriptEditor.app.
Use the ʻosascript` command.
At terminal.app
$ osascript -e 'display notification "Hello World"'
So you get the same result as before.
It can be executed by passing the above command as a character string to the argument of the system
method of the ʻos` module.
notification.py
import os
os.system("osascript -e 'display notification \"Hello World\"'")
If the Python script may be executed in an environment other than Mac, it may be necessary to prevent the desktop notification from being displayed in some environments.
There is a module called platform in the Python standard library, so I used this.
Running platform.system ()
will return the system name as a string like 'Linux'
, 'Darwin'
,'Java'
, 'Windows'
. If you are not sure, an empty string will be returned.
The above is summarized as follows.
notification_matome.py
import os
from platform import system
pf = system()
if pf == "Darwin":
os.system("osascript -e 'display notification \"Hello World\"'")
The notification comes from the "script editor", so I'd like to change it if possible.
Reference
[How to operate the notification center of macOS from python-I suffer from output](http://atc.hateblo.jp/entry/2018/06/25/python%E3%81%8B%E3%82%89macOS % E3% 81% AE% E9% 80% 9A% E7% 9F% A5% E3% 82% BB% E3% 83% B3% E3% 82% BF% E3% 83% BC% E3% 82% 92% E6 % 93% 8D% E3% 82% 8B% E6% 96% B9% E6% B3% 95)
platform --- Refer to the specific information of the running platform — Python 3.8.5 documentation
Recommended Posts