为什么我的脚本只有在剪贴板中有内容时才有效?

Why does my script only work when i have something in the clipboard?

我有一个(长)Applescript 来打开 VPN 连接。但是,如果我在剪贴板中没有文本,它就会停止,而且我似乎不明白为什么。

我想要完成的是将剪贴板中的任何内容(如果有的话)移动到临时变量,将密码放入剪贴板,以便我可以将其粘贴到登录名中 window ,最后把剪贴板放回去。

这是我脚本的(我认为)相关部分:

open_vpn_connection(vpn_name, user_name, app_name, window_name)
set pass_word to getPassword(keychain_name)
local clipBefore
set clipBefore to the clipboard
set the clipboard to pass_word
delay 0.5
tell application "System Events"
    keystroke "v" using command down
    keystroke return
end tell
delay 0.5
set the clipboard to clipBefore

所以基本上,除非我在 运行 脚本之前剪贴板中有内容,否则它会挂起。有人知道为什么吗?

好的,所以我仔细研究了一下,我想我已经找到了原因。对于初学者,我想补充一点,这曾经工作了几年,但大约一年前在 mac 更新中停止工作。

这是我在脚本编辑器中使用的 "proof-of-concept"-脚本:

set clipBefore to the clipboard
log clipBefore
set the clipboard to "banana"
log (the clipboard)
set the clipboard to clipBefore
log (the clipboard)

如果我重新启动 machine,我做的第一件事就是打开脚本编辑器,运行 我的脚本会在日志中得到:

error "An error of type -25133 has occurred." number -25133

我环顾四周,那个错误代码是

badPasteboardFlavorErr = -25133, /* item flavor does not exist*/

,这告诉我系统剪贴板处理有问题?我不能确切地说它是什么时候发生的,但如果我的 machine 被锁定了足够长的时间,我会解锁它并且 运行 脚本有时也会发生。

解决方案总是只执行 ctrl+c 操作,然后再次 运行 脚本。

我通过在剪贴板内容周围添加 try catch 解决了我的脚本(当然在我的部分代码之前和之后做了很多事情):

local clipBefore
set clipBefore to ""
try
    set clipBefore to the clipboard
end try 
set the clipboard to pass_word

因为它只会在剪贴板中没有任何内容时抛出异常,所以现在每次都能正常工作:)