Reputation: 63
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
Upvotes: 6
Views: 14955
Reputation: 116
os.system("open -a /Applications/Safari.app http://www.google.com") for this to work when safari is not the default add -a after open. Cant comment yet (reputation below 50 (: )
Upvotes: 4
Reputation: 85045
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.
Upvotes: 21
Reputation: 37930
This works for me:
os.system("open /Applications/Safari.app http://www.google.com")
Upvotes: 1