AppleScript读取剪贴板路径打开文件报错,如何解决?
AppleScript读取剪贴板路径打开文件报错的解决方法
问题场景
硬编码文件路径的代码可正常打开文件:
tell application "Finder" open POSIX file "/Users/myName/file.pdf" end tell
但读取剪贴板路径的代码运行失败,报错:Finder got an error: Can’t get POSIX file "/Users/myName/file.pdf"
对应代码:
tell application "Finder" set filePath to (the clipboard as text) open POSIX file filePath end tell
问题原因
- 剪贴板中的路径文本可能携带多余的空白字符(换行、空格、制表符)或引号,导致POSIX路径解析失败
- 在Finder的
tell块内直接处理剪贴板,可能受上下文限制影响路径解析
解决代码
-- 先在Finder上下文外处理剪贴板内容 set filePath to (the clipboard as text) -- 清理路径中的多余字符 set cleanedFilePath to my cleanPath(filePath) -- 调用Finder打开文件 tell application "Finder" open POSIX file cleanedFilePath end tell -- 路径清理函数:去除首尾空白和多余引号 on cleanPath(inputPath) -- 去除首尾空白字符 set trimmedPath to my trim(inputPath) -- 去除首尾引号(如果存在) if trimmedPath starts with "\"" and trimmedPath ends with "\"" then return text 2 through -2 of trimmedPath else if trimmedPath starts with "'" and trimmedPath ends with "'" then return text 2 through -2 of trimmedPath else return trimmedPath end if end cleanPath -- 去除首尾空白的辅助函数 on trim(inputText) set AppleScript's text item delimiters to {" ", return, linefeed, tab} set trimmedText to text items of inputText set AppleScript's text item delimiters to "" return trimmedText as text end trim
补充说明
如果不需要通过Finder打开,也可以直接用系统命令调用默认程序,代码更简洁:
set filePath to (the clipboard as text) set cleanedFilePath to my cleanPath(filePath) do shell script "open " & quoted form of cleanedFilePath
内容的提问来源于stack exchange,提问作者Coleman YU
相关产品推荐
相关产品推荐

