Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

macos - Python post osx notification

Using python I am wanting to post a message to the OSX Notification Center. What library do I need to use? should i write a program in objective-c and then call that program from python?


update

How do I access the features of notification center for 10.9 such as the buttons and the text field?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All the other answers here require third party libraries; this one doesn't require anything. It just uses an apple script to create the notification:

import os

def notify(title, text):
    os.system("""
              osascript -e 'display notification "{}" with title "{}"'
              """.format(text, title))

notify("Title", "Heres an alert")

Note that this example does not escape quotes, double quotes, or other special characters, so these characters will not work correctly in the text or title of the notification.

Update: This should work with any strings, no need to escape anything. It works by passing the raw strings as args to the apple script instead of trying to embed them in the text of the apple script program.

import subprocess

CMD = '''
on run argv
  display notification (item 2 of argv) with title (item 1 of argv)
end run
'''

def notify(title, text):
  subprocess.call(['osascript', '-e', CMD, title, text])

# Example uses:
notify("Title", "Heres an alert")
notify(r'Weird/|"!@#$%^&*()
title', r'!@#$%^&*()"')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...