当我有文件路径时,如何检查应用程序是否正在运行?

时间:2011-01-12 14:27:09

标签: applescript

我正在尝试制作一个脚本(除其他外)需要知道某个应用程序是否正在运行。为了获得最大的稳健性,我想通过它的文件路径找到它。或者,如果失败,请通过其名称或包标识符找到它,并检查其文件路径。只是为了使事情复杂化,我有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 - 别名转换为POSIX路径并将它们作为字符串进行比较。我也不能将我拥有的POSIX路径转换为别名,然后进行比较。

那么,我该怎么办?

更新/溶液

保罗R和regulus6633的帽子提示提供了有用的提示!

我应该更具体一点。正如我在下面的一些评论中写的那样,当你只有它的路径时,确定一个是否正在运行并不是所有脚本应该做的。事实上,重点是找到与路径匹配的进程,然后执行一些GUI脚本。即我不能使用简单的ps,因为我需要访问GUI / AppleScript的东西(特别是进程'窗口)。

技术上我可以用ps来获取PID(如下面的regulus6633所示),但AppleScript已经在由另一个shell中运行的Ruby脚本生成的shell中运行,它看起来很混乱。 / p>

结束这样做(这似乎很多,但在我正在做的事情的背景下是必要的):

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

2 个答案:

答案 0 :(得分:1)

我们在Mac上有很多工具,您通常可以找到解决方案。在您的情况下,我同意您不能过滤“应用程序文件”。您可能只能过滤字符串,数字或布尔值。

但是我们确实有其他工具,比如命令行,我们也可以访问objective-c方法。这是一个命令行方法......

set applicationPosixPath to "/Applications/Utilities/AppleScript Editor.app"

try
    do shell script "/bin/ps -ef | grep " & quoted form of applicationPosixPath & " | grep -v grep"
    return "application is running"
on error
    return "application is not running"
end try

答案 1 :(得分:0)

我认为您需要做的就是:

tell application "System Events"
    set theAlias to application file of item 1 of (processes whose bundle identifier is "com.apple.TextEdit")
    set thePath to (the POSIX path of theAlias)
end tell

无论如何,它似乎对我有用......