什么替代了现在已经过时的Carbon.File.FSResolveAliasFile在Python OSX? [英] What replaces the now-deprecated Carbon.File.FSResolveAliasFile in Python on OSX?

查看:377
本文介绍了什么替代了现在已经过时的Carbon.File.FSResolveAliasFile在Python OSX?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2中,我可以使用以下代码解析MacOS别名或符号链接:

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)[0].as_pathname()

其中alias_fp是我很好奇的文件的路径,存储为字符串( source )。

where alias_fp is the path to the file I'm curious about, stored as a string (source).

但是,文档高兴地告诉我,模块的整个Carbon系列已弃用。我应该使用什么?

However, the documentation cheerfully tells me that the whole Carbon family of modules is deprecated. What should I be using instead?

编辑:我相信下面的代码是朝着正确的方向为PyObjC方法的一个步骤。它不解析别名,但它似乎检测到它们。

I believe the code below is a step in the right direction for the PyObjC approach. It doesn't resolve aliases, but it seems to detect them.

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


$ b b

来源

很遗憾,我无法获得@ Milliways的解决方案工作(不了解Cocoa)和我在互联网上的其他地方找到的东西看起来更复杂(也许是处理各种边缘情况?)。

Unfortunately I'm not able to get @Milliways's solution working (knowing nothing about Cocoa) and stuff I find elsewhere on the internet looks far more complicated (perhaps it's handling all kinds of edge cases?).

推荐答案

PyObjC网桥允许您访问NSURL的书签处理,这是现代(向后兼容)

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

这篇关于什么替代了现在已经过时的Carbon.File.FSResolveAliasFile在Python OSX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆