问题描述
我编写了一个 AppleScript 来自动化我的工作设置,只需要最后的润色。我在脚本中将某些内容复制到剪贴板;我需要编辑我复制的文本,只留下最后一行(最好不要打开实际的文本编辑器应用程序,因为这会使我的工作区变得混乱),然后将该行粘贴到 Google Chrome 浏览器中。
到目前为止,在我的脚本的最后一步中,我做了一些导致消息文本输出到终端的事情。然后我将终端中可见的文本复制到剪贴板,如下所示:
tell application "Terminal"
tell front window
set the clipboard to contents of selected tab as text
end tell
end tell
现在我可以粘贴它,就像
...
[I 15:03:31.259 LabApp] Serving notebooks from local directory: /workspace
[I 15:03:31.259 LabApp] The Jupyter Notebook is running at:
[I 15:03:31.259 LabApp] http://1fw5c518af9:1932/?token=5e6d97b348fsy734gd
[I 15:03:31.259 LabApp] or http://88.0.0.1:1932/?token=5e6d97b348fsy734gd
[I 23:56:47.798 LabApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 23:56:47.803 LabApp]
To access the notebook,open this file in a browser:
file:///root/.local/share/jupyter/runtime-open.html
Or copy and paste one of these URLs:
http://1fw5c518af9:1932/?token=5e6d97b348fsy734gd
or http://88.0.0.1:1932/?token=5e6d97b348fsy734gd
这总是以 or *URL*
格式的文本结尾,例如在上面的例子中,它是 or http://88.0.0.1:1932/?token=5e6d97b348fsy734gd
。这与上面的行通过行分隔符和“或”之前的一些尾随空格分隔。
我需要做的是获取该 URL,启动 Google Chrome 浏览器并将其粘贴到那里。
打开谷歌浏览器应该很简单,下面的代码(来自这个tut)带你到Instagram:
tell application "Google Chrome" to activate
tell application "System Events"
key code 37 using command down
delay 0.5
keystroke "https://www.instagram.com/instagram"
delay 1
key code 36
delay 1
end tell
实际上我所需要的只是将剪贴板上的内容编辑为 *URL*
(在上面的示例中,只需 http://88.0.0.1:1932/?token=5e6d97b348fsy734gd
)。之后,我可以从剪贴板(在教程中输入 Instagram 的位置)粘贴它。
在尝试下面@user3439894 的可爱回答后,我发现情况有点复杂:
- 在最后的后面有不可预知的空行“” 链接。
- 我也想知道最后是否有空格 还有
我已经知道 http://88.0.0.1 的形式(它总是这样)所以有没有办法搜索它然后用后面的链接的其余部分抓取它? (能够以“”或换行符分隔结尾会很棒)
编辑2:
如果 http://88.0.0.1...
出现多次,我们只想选择这些网址中的一个 - 它们可能大致相同,但选择最后一个最安全.
解决方法
我需要做的是获取该 URL,启动 Google Chrome 浏览器并将其粘贴到那里。
&
这总是以 or *URL*
格式的文本结尾,例如在上面
例如它会是 or http://88.0.0.1:1932/?token=5e6d97b348fsy734gd
。这是分开的
从上面的行加上一个行分隔符加上一些尾随空格
在“或”之前。
&
如果 http://88.0.0.1...
出现多次,我们希望
仅选择这些 URL 中的一个 - 它们通常是
相同,但选择最后一个最安全。
如果您想要做的是从所选标签的内容中获取以http://88
开头的最后一个URL >在终端中的前窗,那么这里有一种不使用剪贴板的方法,并在谷歌浏览器中打开它,和也无需使用UI 脚本。
换句话说,无需更改剪贴板上的文本或击键 URL,因为您只需告诉 Google Chrome 用于 URL 的内容。
示例 AppleScript 代码:
tell application "Terminal" to ¬
set theTextFromTerminal to ¬
the contents of ¬
the selected tab of ¬
the front window ¬
as text
set theURL to ¬
the last paragraph of ¬
(do shell script ¬
"grep -o 'http://88.*$' <<< " & ¬
theTextFromTerminal's quoted form & ¬
"; exit 0")
if theURL is "" then return
if theURL does not start with ¬
"http://88." then return
tell application "Google Chrome"
activate
delay 1
if exists front window then
make new tab at ¬
end of front window ¬
with properties {URL:theURL}
else
set URL of ¬
the active tab of ¬
(make new window) to theURL
end if
end tell
注意:示例 AppleScript 代码就是这样,没有任何包含的错误处理不包含任何额外的错误处理。用户有责任根据需要添加任何错误处理。查看 try 中的 error statement 和 AppleScript Language Guide statement。另见Working with Errors。此外,在适当的情况下,可能需要在事件之间使用 delay command,例如delay 0.5
,适当设置 delay 的 value。