使用 tell 通过 applescript(osascript) 生成新应用程序后获取进程 ID

Get process id after spawning new application via applescript(osascript) using tell

tell application "Google Chrome"

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

end tell

上面的命令产生了一个 google chrome 的实例。我想得到这个进程的进程id,以便以后杀掉它。请注意,我使用 Google chrome 为例,但我可以多次生成任何进程。只需要获取进程ID。

您可以存储对您在变量中创建的 window 的引用,稍后使用该变量将其关闭。下面打开两个windows(to Google和Yahoo),等三秒,关闭Google window:

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

如果您想在多个 运行 脚本中保留对 window 的引用(例如,您 运行 脚本一次打开 window , 然后 运行 稍后再次关闭它)使变量成为 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