【发布时间】:2013-09-13 05:49:45
【问题描述】:
我正在尝试使脚本(除其他外)需要知道某个应用程序是否正在运行。为了获得最大的稳健性,我想通过它的文件路径找到它。或者,如果失败,则通过其名称或包标识符找到它,并检查其文件路径。只是为了使事情复杂化,我有 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
我收到alias Macintosh HD:Applications:TextEdit.app:
太好了,但我无法将其与任何东西相提并论!我什至无法将 application file-alias 转换为 POSIX 路径并将它们作为字符串进行比较。我也不能将我拥有的 POSIX 路径翻译成别名,然后进行比较。
那么,我该怎么办?
更新/解决方案
向 Paul R 和 regulus6633 提供有用的提示!
我可能应该更具体一点。正如我在下面的一些 cmets 中所写的那样,当你只有它的路径时确定一个是否正在运行并不是脚本应该做的全部。重点其实是定位匹配路径的进程,然后做一些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)
bundleIdentifier 参数不是必需的,但它通过缩小进程列表大大加快了一切速度。如果你想让它只使用路径,你可以这样做
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
【问题讨论】:
标签: applescript