Ewa*_*noy 10 applescript shell-script macos
我正在尝试生成一个基于 Applescript 的 shell 命令,该命令告诉 Mac OS X 中的预览应用程序关闭特定窗口。
#!/bin/sh
osascript <<EOF
tell application "Preview"
close "$1"
end tell
EOF
Run Code Online (Sandbox Code Playgroud)
但这不起作用:我收到错误消息
25:52: execution error: Preview got an error: "musixdoc.pdf" doesn’t understand the close message. (-1708)
Run Code Online (Sandbox Code Playgroud)
slh*_*hck 12
默认情况下,AppleScripting Preview 将不起作用,因为 Preview 缺少必要的字典。要解决此问题,请在此处查看Lauri 的回答,其中解释NSAppleScriptEnabled了 Preview.app 的设置。
退出 Preview.app,然后打开终端并输入:
sudo defaults write /Applications/Preview.app/Contents/Info NSAppleScriptEnabled -bool true
sudo chmod 644 /Applications/Preview.app/Contents/Info.plist
sudo codesign -f -s - /Applications/Preview.app
Run Code Online (Sandbox Code Playgroud)
关闭任何命名应用程序窗口的命令如下所示:
tell application "Preview" to close window 1
Run Code Online (Sandbox Code Playgroud)
...或者如果你想关闭一个命名的文档窗口,例如foo.jpg:
告诉应用程序“预览”关闭(名称为“ foo.jpg ”的每个窗口)
所以,在你的 shell 脚本中,这将是:
#!/bin/sh
osascript <<EOF
tell application "Preview"
close (every window whose name is "$1")
end tell
EOF
Run Code Online (Sandbox Code Playgroud)
在这里,传递给脚本的第一个参数是您要关闭的窗口的名称,例如./quit.sh foo.jpg. 请注意,如果您的文件包含空格,则必须引用文件名,例如./quit.sh "foo bar.jpg".
或者,如果您想从任何应用程序关闭任意窗口,请使用以下命令:
#!/bin/sh
osascript <<EOF
tell application "$1"
close (every window whose name is "$2")
end tell
EOF
Run Code Online (Sandbox Code Playgroud)
在这里,你会使用./quit.sh Preview foo.jpg例如。
如果要关闭属于某个文档的窗口,但要提供文件名,则需要其他内容。这是因为多页 PDF 可以显示为foo.pdf (Page 1 of 42),但您只想传递foo.pdf给 AppleScript。
在这里,我们遍历窗口并将文件名与传递给脚本的参数进行比较:
osascript <<EOF
tell application "Preview"
set windowCount to number of windows
repeat with x from 1 to windowCount
set docName to (name of document of window x)
if (docName is equal to "$1") then
close window x
end if
end repeat
end tell
EOF
Run Code Online (Sandbox Code Playgroud)
现在您可以简单地调用./quit.sh foo.pdf. 一般来说,对于所有具有命名文档窗口的应用程序,这将是:
osascript <<EOF
tell application "$1"
set windowCount to number of windows
repeat with x from 1 to windowCount
set docName to (name of document of window x)
if (docName is equal to "$2") then
close window x
end if
end repeat
end tell
EOF
Run Code Online (Sandbox Code Playgroud)
Preview.app 是这些应用程序之一,一旦其最后一个文档窗口关闭,它就会自动退出。这样做是为了节省内存和“清理”。要禁用此行为,请运行以下命令:
defaults write -g NSDisableAutomaticTermination -bool TRUE
Run Code Online (Sandbox Code Playgroud)
当然,要撤消该操作,请更改TRUE为FALSE。
最后,我建议将您的脚本放入一个在您的 shell 中始终可用的函数中。为此,请将脚本添加到您的~/.bash_profile. 如果此文件不存在,则创建它。
cw() {
osascript <<EOF
tell application "$1"
set windowCount to number of windows
repeat with x from 1 to windowCount
set docName to (name of document of window x)
if (docName is equal to "$2") then
close window x
end if
end repeat
end tell
EOF
}
Run Code Online (Sandbox Code Playgroud)
保存 bash 配置文件并重新启动 shell 后,您就可以cw Preview foo.pdf从任何地方调用。
| 归档时间: |
|
| 查看次数: |
19929 次 |
| 最近记录: |