gpt4 book ai didi

javascript - 如何通过 osascript 处理同一应用程序的两个实例

转载 作者:行者123 更新时间:2023-11-30 16:57:53 26 4
gpt4 key购买 nike

谁能想出解决 osascript 按名称索引瓶颈的方法,因为它引用了同一应用程序的多个实例?

如果我们获得两个进程 ID——同一个应用程序的两个不同实例中的每一个,osascript 返回同一个实例以换取任何一个 pid——就好像它首先将 pid 映射到一个应用程序名称,然后检索第一个具有该名称的应用程序。

例如,启动两个不同的 VLC.app 实例,播放两个不同的视频文件,如下所示:

open -na /Applications/VLC.app ~/fileA.m4v
open -na /Applications/VLC.app ~/fileB.m4v

然后获取两个单独的应用程序进程 ID,例如:

echo "$(ps -ceo pid=,comm= | awk '/VLC/ { print $1}')"

然后我们可以使用 Applescript 或 Yosemite JXA Javascript 从任一 pid 获取对应用程序对象的引用。

然而,事实证明,无论我们提供哪个进程 ID,我们总是返回对同一实例的引用,运行相同的视频文件,就好像 osascript 只是将 pid 转换为应用程序名称,然后总是返回匹配该名称的第一个进程。

用于应用程序的 Yosemite Javascript:

function run() {
var app = Application.currentApplication();
app.includeStandardAdditions = true;

var lstVLC = app.doShellScript(
"echo \"$(ps -ceo pid=,comm= | awk '/VLC/ { print $1}')\""
).split(/[\r\n]/).map(Number).map(Application);

return {
firstInstance: lstVLC[0].windows[0].name(),
secondInstance: lstVLC[1].windows[0].name()
};
}

苹果脚本:

on run {}
set strCMD to "echo \"$(ps -ceo pid=,comm= | awk '/VLC/ { print $1}')\""
set lstNum to paragraphs of (do shell script strCMD)
repeat with i from 1 to length of lstNum
set item i of lstNum to (item i of lstNum) as number
end repeat


tell application "System Events"
set oProcA to first application process where unix id = (item 1 of lstNum)
set oProcB to first application process where unix id = (item 2 of lstNum)
end tell

return [name of first window of oProcA, name of first window of oProcB]
end run

对分别为每个实例编写脚本的途径有什么想法吗?

最佳答案

对于每个实例,从与特定进程相同的行中询问窗口的名称,如下所示:

set windowNames to {}
set lstNum to paragraphs of (do shell script "ps -ceo pid=,comm= | awk '/VLC/ { print $1}'")
tell application "System Events" to repeat with i in lstNum
set end of windowNames to name of first window of (first application process where unix id = i)
end repeat
return windowNames

关于javascript - 如何通过 osascript 处理同一应用程序的两个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29391225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com