Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening and using Safari

Tags:

python

macos

I am relatively new to the mac world. My question concerns opening an application using python on mac osx. From what I've found so far, it seems as if applications are stored in app format that are actually directories. Are these parsed somehow by the OS when opening the app? I would like to open Safari using python and it is in my /Applications/Safari.app directory. Is there a specific binary I should be passing to os.system or should I be going about it in a completely different way? My end goal is to have safari open a local html file, close it then open another local html file.

Thanks, -John

like image 831
user583599 Avatar asked Jan 20 '11 20:01

user583599


People also ask

Can I use both Chrome and Safari?

Yes. All browsers act independently, allowing you to run multiple browsers at the same time. The only issue you may experience is browsers "fighting" over which should be the default.

How do I open up Safari?

If you don't see Safari on your Home Screen, you can find it in App Library and add it back. On the Home Screen, swipe left to access App Library. Enter “Safari” in the search field. , then tap Add to Home Screen.


1 Answers

The Python standard library includes the webbrowser module which allows you to open a new browser window or tab in a platform-independent way. It does support Safari on OS X if it is the user's default:

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

But webbrowser does not support closing a browser window. For that level of control, you are best off using Safari's 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 web page displayed in the tab you opened:

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

Safari's Apple Events interface is somewhat non-intuitive (unfortunately, that's not unusual with Mac applications). There are references out there if you need to do more complex stuff. But Python and py-appscript give you a solid base to work from.

like image 169
Ned Deily Avatar answered Nov 15 '22 07:11

Ned Deily