How to open an application in Mac OS using Python

MacOS

Question or issue on macOS:

I want to open an application like TextEdit or Firefox in Mac OS using Python and wait till the applications exits. I can’t figure out exact command to open an app and wait.

How to solve this problem?

Solution no. 1:

I don’t know how to do it in applescript, but you can do this by using the /usr/bin/open UNIX-level OS X command. This snippet will open TextEdit.app and block, waiting for it to quit before continuing:

import subprocess

subprocess.call(
    ["/usr/bin/open", "-W", "-n", "-a", "/Applications/TextEdit.app"]
    )

Look at the open man page (man open) and the python subprocess module documentation for more details.

Solution no. 2:

AppleScript:

tell app "Whatever you want" to open

Call from Python

import os
os.system("""osascript -e 'tell app "Safari" to open'""")

Solution no. 3:

You can open any application like this example

import os

os.system("open /Applications/Google\ Chrome.app")
os.system("open /Applications/Todoist.app")
os.system("open /Applications/WhatsApp.app")

Solution no. 4:

You can close any app on osx (like Chrome or Safari) with this in python:

import os

os.system("pkill Chrome")

Hope this helps!