【问题标题】:Get process id after spawning new application via applescript(osascript) using tell使用tell通过applescript(osascript)生成新应用程序后获取进程ID
【发布时间】:2020-10-03 07:24:33
【问题描述】:
tell application "Google Chrome"

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

end tell

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

【问题讨论】:

  • 这段代码不会每次都产生一个新进程;它只是在 Chrome 应用程序中打开一个新窗口(如果 Chrome 没有运行,则启动一次)。您是在尝试打开多个并发进程,还是在尝试跟踪您使用此代码打开的窗口?
  • 想法是使用它打开一个进程并获取它的 id,以便我以后可以通过编程方式关闭它
  • 让我确定我们说的是同一种语言。您不想拥有一个带有(比如说)五个窗口的 Google Chrome 实例,而是希望拥有五个 Google Chrome 实例,每个实例带有一个窗口?这是更典型的 MS Windows 环境,但如果你真的想的话,你可以在 MacOS 上做。我的观点是,您编写的代码不会打开多个 Chrome 实例;它会在一个 Chrome 实例中打开多个窗口。
  • 我需要您更清楚地了解您要尝试完成什么。询问每个窗口的进程 ID 没有意义,因为(在 MacOS 上)它们通常都具有相同的进程 ID。
  • 我不确定这里最好的做法是什么。我的目标是打开窗口/实例(如果尚未运行)并能够稍后以编程方式关闭它。我认为最好的方法是跟踪所有新进程 ID 并在以后杀死它们。

标签: macos process applescript macos-catalina osascript


【解决方案1】:

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

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

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

【讨论】:

  • 嘿,你能不能分享一下如何使这个变量成为属性的例子,因为目标是通过不同的脚本关闭这些窗口
  • 这对我不起作用。它在每次执行脚本时打开 2 个新窗口。如果我做错了什么,请告诉我。
  • @knowbalpreet:你的意思是你有 2 个窗口,然后是 4 个,然后是 6 个,然后是 8 个?您是从脚本编辑器运行它吗?您是否使用了全新的脚本编辑器窗口?不要重新编译脚本只是运行它;如果你重新编译它会将属性值清零。
  • @knowbalpreet:建议:如果您遇到问题,永远说“它不起作用”或报告您得到的错误结果是不够的。你必须说出做了什么。问题不在于脚本或计算机;问题(总是)与用户如何与计算机交互。你必须说出你采取了哪些步骤,即使它们看起来与你无关,否则没有人能帮助你。
  • 对不起我的错。我对 Applescript 没有太多经验,我从终端运行这个脚本。这是我试图从 CLI pastebin.com/aAPgFmfp 运行的内容。我想独立运行这个脚本,一次启动所有应用程序,然后关闭它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
  • 2014-04-05
相关资源
最近更新 更多