获取 Mac 上文件的元数据 "Where from"

Obtaining metadata "Where from" of a file on Mac

我正在尝试获取位于 MacOS.

中文件的“获取信息”上下文菜单中的“来源”扩展文件属性

例子

当右键单击文件并显示信息时,它会显示此元数据。

下图中高亮部分是我要获取的信息(下载文件的网址link)。

我想通过 Python 使用这个 Mac 特定的函数。 我想过使用 OS 工具,但找不到任何工具。

macOS 将 "Where from" 属性等元数据存储在键 com.apple.metadata:kMDItemWhereFroms 下。

import xattr

value = xattr.getxattr("sublime_text_build_4121_mac.zip",'com.apple.metadata:kMDItemWhereFroms').decode("ISO-8859-1")

print(value)

'bplist00¢\x01\x02_\x10@https://download.sublimetext.com/sublime_text_build_4121_mac.zip_\x10\x1chttps://www.sublimetext.com/\x08\x0bN\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00m'

很久以前我遇到过类似的问题。我们没有用Python来解决。

TL;DR: 获取 扩展属性 就像 MacOS 的“Where from”通过例如pip-install pyxattr 并使用 xattr.getxattr("file.pdf", "com.apple.metadata:kMDItemWhereFroms").

文件的扩展属性

这些 extended file attributes 就像您在 MacOS 中的“Where From”(自 10.4 起)存储不被文件系统解释的元数据。它们适用于不同的操作系统。

使用命令行

您还可以使用以下工具在命令行上查询它们:

exiftool -MDItemWhereFroms -MDItemTitle -MDItemAuthors -MDItemDownloadedDate /path/to/file
xattr -p -l -x /path/to/file

在 MacOS 多个 attributes are displayed in property-list format 上,因此使用 -x 选项来获得十六进制输出。

使用Python

pointed out the missing link keywords. Such common and appropriate terms are helpful to search Python Package Index (PyPi):

通过关键字搜索 PyPi:扩展文件属性元数据

例如要列出和获取属性使用(改编自 pyxattr's official docs

import xattr

xattr.listxattr("file.pdf")
# ['user.mime_type', 'com.apple.metadata:kMDItemWhereFroms']
xattr.getxattr("file.pdf", "user.mime_type")
# 'text/plain'
xattr.getxattr("file.pdf", "com.apple.metadata:kMDItemWhereFroms")
# ['https://example.com/downloads/file.pdf']

但是,您必须转换以 plist 格式存储的 MacOS 特定元数据,例如使用 plistlib.

MacOS

上的文件元数据

Mac OS X 10.4 (Tiger) 引入了 Spotlight 一个用于提取(或收获)、存储、索引和查询 元数据的系统.它为搜索和索引提供了一个集成的全系统服务。

此元数据存储为具有 keys prefixed with com.apple.metadata: 扩展文件属性 。例如,“Where from”属性具有关键字 com.apple.metadata:kMDItemWhereFroms.

使用Python

使用 osxmetadata 以使用与 MacOS 的 md* utils:

类似的功能
from osxmetadata import OSXMetaData

filename = 'file.pdf'
meta = OSXMetaData(filename)

# get and print "Where from" list, downloaded date, title
print(meta.wherefroms, meta.downloadeddate, meta.title)

另见