如何使用 AppleScript 或 shell 脚本在 OSX 中获取文件 URL? [英] How to get the a file URL in OSX with AppleScript or a shell script?
问题描述
我尝试编写一个键盘大师快捷方式来给我一个文件的 URL(就像路径查找器输出的那样).
I try to hack together a Keyboard Maestro shortcut to give me the URL to a file (just like the ones Path Finder outputs).
到目前为止,我使用以下 AppleScript 并将 空格 替换为 %20:
So far I use the following AppleScript and replace the spaces with %20:
tell application "Finder"
set sel to the selection as text
set the clipboard to POSIX path of sel
end tell
然后我简单地附加 file://localhost/
.
问题在于特殊字符,例如我的桌面上有以下文件夹:
The problem is when it comes to special characters, for example I got the following folder on my Desktop:
我的输出:file://localhost//Users/patte/Desktop/#%20Old%20files
正确的输出应该转换哈希:file://localhost/Users/patte/Desktop/%23%20Old%20files
The correct output should convert the hash: file://localhost/Users/patte/Desktop/%23%20Old%20files
使用 AppleScript 或 Shell 脚本的解决方案会很棒,因为我能够将其合并.我也尝试过将剪贴板设置为(获取选择)的第一项的 URL
但这对我不起作用 - 也许我做错了.
A solution with AppleScript or Shell script would be great since I'm capable of incorporate this. I also tried set the clipboard to URL of the first item of (get the selection)
but this hasn't worked for me - maybe I did it wrong.
另一种选择是对特殊字符进行编码的脚本 - 我也可以使用它,但我不确定要将什么转换为什么 - 否则我会寻找它.
Another option would be a script that encodes the special characters - I could also work with that, but I'm not sure what to convert into what - else I'd have look for it.
推荐答案
这几乎是逐字从 this answer 即在将 file://localhost
添加到字符串的开头之前,利用 python 的 urllib 适当地引用字符串
this is lifted almost verbatim from this answer i.e. leverage python's urllib to quote the string appropriately before adding in the file://localhost
to the start of the string
on path2url(thepath)
return do shell script "python -c \"import urllib, sys; print (urllib.quote(sys.argv[1]))\" " & quoted form of thepath
end path2url
tell application "Finder"
set sel to the selection as text
set the clipboard to "file://localhost" & my path2url(POSIX path of sel)
end tell
我在打印内容周围添加了括号,以使 python 脚本在 python 2.x 和 python 3 之间兼容.
I've added parentheses around the print in order to make the python script compatible between python 2.x and python 3.
这篇关于如何使用 AppleScript 或 shell 脚本在 OSX 中获取文件 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!