首页 > 解决方案 > 使用tell通过applescript(osascript)生成新应用程序后获取进程ID

问题描述

tell application "Google Chrome"

make new window
open location "https://google.com"

end tell

上面的命令生成了一个 google chrome 的实例。我想获取此进程的进程 ID,以便以后可以将其杀死。请注意,例如,我使用的是 Google chrome,但我可以多次生成任何进程。只需要获取进程ID。

标签: macosprocessapplescriptmacos-catalinaosascript

解决方案


您可以将对您创建的窗口的引用存储在变量中,然后使用该变量将其关闭。下面打开两个窗口(对谷歌和雅虎),等待三秒钟,关闭谷歌窗口:

tell application "Google Chrome"
    set windowGoog to make new window
    tell windowGoog to open location "https://google.com"
    set windowYah to make new window
    tell windowYah to open location "http://Yahoo.com"
end tell

(*
    You can do whatever you need to do here. I've added a three second delay just 
    to give a sense of time, but that's just for show.
*)
delay 3

tell application "Google Chrome"
    close windowGoog
end tell

如果您想在脚本的多次运行中保持对窗口的引用(例如,您运行脚本一次以打开窗口,然后再次运行以关闭它)创建变量 a property,并使用if语句检查它是否有一个值,像这样:

(* 
    These two lines set 'windowGoog' and 'windowYah' to 'missing value' on the 
    first run, and then remember whatever value you set until the next time 
    you recompile the script
*)
property windowGoog : missing value
property windowYah : missing value

tell application "Google Chrome"
    if windowGoog is missing value then
        set windowGoog to make new window
        tell windowGoog to open location "https://google.com"
    else
        close windowGoog
        set windowGoog to missing value
    end if
    if windowYah is missing value then
        set windowYah to make new window
        tell windowYah to open location "http://Yahoo.com"
    else
        close windowYah
        set windowYah to missing value
    end if
end tell

推荐阅读