What replaces the now-deprecated Carbon.File.FSResolveAliasFile in Python on OSX?

后端 未结 3 1707
夕颜
夕颜 2020-12-21 18:33

In Python 2, I can use the following code to resolve either a MacOS alias or a symbolic link:

from Carbon import File
File.FSResolveAliasFile(alias_fp, True)         


        
3条回答
  •  隐瞒了意图╮
    2020-12-21 19:11

    The PyObjC bridge lets you access NSURL's bookmark handling, which is the modern (backwards compatible) replacement for aliases:

    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, 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
    

提交回复
热议问题