我正在尝试制作一个脚本(除其他外)需要知道某个应用程序是否正在运行。为了获得最大的鲁棒性,我想通过它的文件路径找到它。或者,如果失败,请通过名称或包标识符找到它,然后检查其文件路径。只是为了让事情变得复杂,我有 POSIX 形式的应用程序路径
我想做的是这样的(此处以 TextEdit 为例)
tell application "System Events"
item 1 of (processes whose application file is "/Applications/TextEdit.app")
end tell
但这不起作用...
我不是 AppleScript 天才,但我发现我至少可以从其包标识符中找到正在运行的进程,然后将其文件作为无用的“别名”获取:
tell application "System Events"
application file of item 1 of (processes whose bundle identifier is "com.apple.TextEdit")
end tell
I get alias Macintosh HD:Applications:TextEdit.app:
太棒了,但我无法将其与任何东西进行比较!我什至无法翻译application file
- POSIX 路径的别名并将它们作为字符串进行比较。我也无法将 POSIX 路径转换为别名,然后进行比较。
那么,我该怎么办?
更新/解决方案
向 Paul R 和 regulus6633 提供有用的提示表示敬意!
我可能应该更具体一点。正如我在下面的一些评论中所写的那样,当您只有路径时确定 an 是否正在运行并不是脚本应该做的全部事情。事实上,重点是找到与路径匹配的进程,然后执行一些 GUI 脚本。 IE。我不能使用简单的ps
因为我需要访问 GUI/AppleScript 的东西(特别是进程的窗口)。
从技术上讲我可以做一个ps
获取 PID(如下 regulus6633 建议的那样),但 AppleScript 已经在由在另一个 shell 中运行的 Ruby 脚本生成的 shell 中运行,而且看起来很混乱。
最终这样做了(这看起来很多,但在我正在做的事情的背景下这是必要的):
on getProcessByPOSIXPath(posixPath, bundleID)
-- This file-as-alias seems really complex, but it's an easy way to normalize the path endings (i.e. trailing slash/colon)
set pathFile to (POSIX file posixPath) as alias
set thePath to pathFile as text
tell application "System Events"
repeat with activeProcess in (processes whose bundle identifier is bundleID)
try
set appFile to application file of activeProcess
if (appFile as text) is equal to thePath then return activeProcess
end try
end repeat
return null
end tell
end getProcessByPOSIXPath
请注意,posixPath
参数必须是应用程序包的路径(例如“/Applications/TextEdit.app/”,带或不带尾部斜杠),而不是包内的实际可执行文件。
该函数将返回与给定 POSIX 路径匹配的进程(如果未找到则返回 null)
The bundleIdentifier
争论不是必要的,但它会加速一切a lot通过缩小进程列表。如果您希望仅使用路径来完成此操作,您可以这样做
on getProcessByPOSIXPath(posixPath)
set pathFile to (POSIX file posixPath) as alias
set thePath to pathFile as text
tell application "System Events"
repeat with activeProcess in processes
try
set appFile to application file of activeProcess
if (appFile as text) is equal to thePath then return activeProcess
end try
end repeat
return null
end tell
end getProcessByPOSIXPath