Opening and using Safari

I am relatively new to the Mac world. My question is about opening an application using python on mac osx. From what I have found so far, it seems that applications are stored in the application format, which are actually directories. Are they developed in some way by the OS when opening the application? I would like to open Safari using python, and it is located in my /Applications/Safari.app directory. Is there a specific binary that I have to transfer to os.system, or should I go about it in a completely different way? My ultimate goal is to open Safari a local html file, close it, and then open another local html file.

Thanks, John

+5
source share
3 answers

The Python standard library includes a webbrowser module that allows you to open a new browser window or tab, regardless of platform. It supports Safari on OS X if it is the default user:

>>> import webbrowser
>>> webbrowser.open("http://stackoverflow.com")

But webbrowserdoes not support closing the browser window. For this level of control, your best bet is to use the Safari Apple Event scripting interface by installing py-appscript .

>>> from appscript import *
>>> safari = app("Safari")
>>> safari.make(new=k.document,with_properties={k.URL:"http://stackoverflow.com"})
>>> safari.windows.first.current_tab.close()

If you just want to change the webpage displayed on the open tab:

>>> safari.windows.first.current_tab.URL.set("http://www.google.com")
>>> safari.windows.first.current_tab.URL.set("http://www.python.com")

The Safari Apple Events interface is somewhat unintuitive (unfortunately, this is unusual for Mac apps). There are links if you need to do more complex things. But Python and py-appscript give you a solid foundation to work with.

+15

:

os.system("open /Applications/Safari.app http://www.google.com")
0

os.system ("open -a / Applications / Safari.app http://www.google.com ") for this to work when safari is not the default -a after opening. Cant comment yet (reputation below 50 (:)

0
source

All Articles