如何使用AppleScript或Shell脚本在OSX中获取文件URL? [英] How to get the a file URL in OSX with AppleScript or a shell script?
问题描述
我尝试一起破解Keyboard Maestro快捷方式,以便为我提供文件的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 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屋!