[英]Get path from OS X file reference URL alias (file:///.file/id=…)
In PyQt4 on Apple Mac OS X, we get a file reference URL to a drag-and-dropped file in the following format:在 Apple Mac OS X 上的 PyQt4 中,我们获得了拖放文件的文件引用 URL ,格式如下:
file:///.file/id=123456.78901
This, interestingly, is not a valid file URL, or at least it doesn't transparently resolve in most applications — there is no /.file/id=...
file in the filesystem.有趣的是,这不是一个有效的文件 URL,或者至少在大多数应用程序中它不能透明地解析——文件系统中没有/.file/id=...
文件。
Using just shell, how do I dereference this NSURL or file reference or alias (or whatever it's called) into a valid path to file on the filesystem?仅使用 shell,我如何将此 NSURL 或文件引用或别名(或任何名称)取消引用到文件系统上文件的有效路径中?
In Swift you can use URL.standardized to get the valid path from a reference URL.在 Swift 中,您可以使用 URL.standardized 从参考 URL 获取有效路径。 So in Swift 4 - to get the file name from a drag-and-dropped file you'd do something like...因此,在 Swift 4 中 - 要从拖放文件中获取文件名,您可以执行以下操作...
let fileType = NSPasteboard.PasteboardType (kUTTypeFileURL as String)
extension NSPasteboardItem {
func fileURL ()->URL? {
if let refURL = self.string(forType: fileType) {
return URL (fileURLWithPath: refURL).standardized
}
return nil
}
}
One can use osascript
, an AppleScript interpreter available on default OS X installs, run with the following script:可以使用osascript
,这是默认 OS X 安装上可用的AppleScript解释器,使用以下脚本运行:
osascript -e 'get posix path of posix file "file:///.file/id=123.456" -- kthxbai'
Prints /Users/josh/Downloads/paste-10837081.py
.打印/Users/josh/Downloads/paste-10837081.py
。
那是一个 NSURL 对象,从中获取路径:
NSString *filePath = [fileURL path];
This can also be accomplished in Python using the PyObjC bridge.这也可以使用 PyObjC 桥在 Python 中完成。
from Foundation import NSURL # depends on PyObjC
# convert a URL file reference to a POSIX path
NSURL.URLWithString_('file:///.file/id=6571367.8602676692').path()
# convert a path file reference to a POSIX path
NSURL.fileURLWithPath_('/.file/id=6571367.8602676692').path()
Be sure you to select the appropriate NSURL method for your data type or else you'll get the wrong value back.请确保为您的数据类型选择合适的 NSURL 方法,否则您将得到错误的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.