简体   繁体   English

如何使用 Python 在 Mac OS 中打开应用程序

[英]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.我想在 Mac OS 中使用 Python 打开 TextEdit 或 Firefox 等应用程序,然后等待应用程序退出。 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.我不知道如何在 applescript 中执行此操作,但是您可以使用/usr/bin/open UNIX 级 OS X 命令来执行此操作。 This snippet will open TextEdit.app and block, waiting for it to quit before continuing:此代码段将打开 TextEdit.app 并阻止,在继续之前等待它退出:

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.查看打开的手册页 ( man open ) 和 python子进程模块文档以获取更多详细信息。

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从 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:你可以在 python 中关闭任何应用程序(如 Chrome 或 Safari):

import os

os.system("pkill Chrome")

This works for me on Mac OS 11.1:这在 Mac OS 11.1 上对我有用:

import os

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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