gpt4 book ai didi

python - 什么替代了 OSX 上 Python 中现已弃用的 Carbon.File.FSResolveAliasFile?

转载 作者:行者123 更新时间:2023-12-01 05:26:28 25 4
gpt4 key购买 nike

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

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

关于python - 什么替代了 OSX 上 Python 中现已弃用的 Carbon.File.FSResolveAliasFile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21244781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com