简体   繁体   中英

How to open an application in Mac OS using Python

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.

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.

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")

AppleScript:

tell app "Whatever you want" to open

Call from Python

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

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

import os

os.system("pkill Chrome")

This works for me on Mac OS 11.1:

import os

os.system("open -a TextEdit")
print("Done and not blocking")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM