在
Python 2中,我可以使用以下代码来解析MacOS别名或符号链接:
from Carbon import File File.FSResolveAliasFile(alias_fp,True)[0].as_pathname()
其中alias_fp是我很好奇的文件的路径,存储为字符串(source).
但是,the documentation cheerfully tells me that the whole Carbon family of modules is deprecated.我应该使用什么呢?
编辑:我相信下面的代码是朝着PyObjC方法的正确方向迈出的一步.它不解析别名,但它似乎检测到它们.
from AppKit import NSWorkspace def is_alias (path): uti,err = NSWorkspace.sharedWorkspace().typeOfFile_error_( os.path.realpath(path),None) if err: raise Exception(unicode(err)) else: return "com.apple.alias-file" == uti
(source)
不幸的是,我无法让@ Milliways的解决方案工作(对Cocoa一无所知),stuff I find elsewhere on the internet看起来要复杂得多(也许它处理各种边缘情况?).
解决方法
PyObjC桥允许您访问NSURL的书签处理,这是别名的现代(向后兼容)替代:
import os.path from Foundation import * def target_of_alias(path): url = NSURL.fileURLWithPath_(path) bookmarkData,error = NSURL.bookmarkDataWithContentsOfURL_error_(url,None) if bookmarkData is None: return None opts = NSURLBookmarkResolutionWithoutUI | NSURLBookmarkResolutionWithoutMounting resolved,stale,error = NSURL.URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(bookmarkData,opts,None,None) return resolved.path() def resolve_links_and_aliases(path): while True: alias_target = target_of_alias(path) if alias_target: path = alias_target continue if os.path.islink(path): path = os.path.realpath(path) continue return path
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。