gpt4 book ai didi

python - 在 OS X 上,是否可以从纯 Python 获取用户库目录?

转载 作者:太空宇宙 更新时间:2023-11-04 10:16:32 25 4
gpt4 key购买 nike

我正在编写一个纯 Python 库,出于各种原因,我非常希望避免要求用户安装任何二进制扩展。但是,在 OS X 上运行时,我还想找到用户库目录 (~/Library),这样我就可以在那里存储一些配置数据,我的理解是对于 Very Valid And Vague But重要原因 正确的方法不是仅仅在我的代码中编写 ~/Library,而是通过询问 OS X 目录在哪里以及一些代码,如

[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
NSUserDomainMask,
YES)
objectAtIndex:0];

当然,这段代码是Objective-C的,不是Python的,所以不能直接拿来用。如果它是纯 C,我会使用 ctypes 从 Python 调用它,但事实并非如此。有什么方法可以从 Python 进行此调用,而无需在 Objective-C 中编写扩展模块或要求用户安装一些扩展模块,如 PyObjC?或者,如果我像其他人一样放弃并硬编码 ~/Library,那么会发生什么可怕的事情吗?

最佳答案

好吧,它是引擎盖下的纯 C,因此您可以使用 ctypes 模块实现相同的结果:

from ctypes import *

NSLibraryDirectory = 5
NSUserDomainMask = 1

def NSSearchPathForDirectoriesInDomains(directory, domainMask, expand = True):
# If library path looks like framework, OS X will search $DYLD_FRAMEWORK_PATHs automatically
# There's no need to specify full path (/System/Library/Frameworks/...)
Foundation = cdll.LoadLibrary("Foundation.framework/Foundation")
CoreFoundation = cdll.LoadLibrary("CoreFoundation.framework/CoreFoundation");

_NSSearchPathForDirectoriesInDomains = Foundation.NSSearchPathForDirectoriesInDomains
_NSSearchPathForDirectoriesInDomains.argtypes = [ c_uint, c_uint, c_bool ]
_NSSearchPathForDirectoriesInDomains.restype = c_void_p

_CFRelease = CoreFoundation.CFRelease
_CFRelease.argtypes = [ c_void_p ]

_CFArrayGetCount = CoreFoundation.CFArrayGetCount
_CFArrayGetCount.argtypes = [ c_void_p ]
_CFArrayGetCount.restype = c_uint

_CFArrayGetValueAtIndex = CoreFoundation.CFArrayGetValueAtIndex
_CFArrayGetValueAtIndex.argtypes = [ c_void_p, c_uint ]
_CFArrayGetValueAtIndex.restype = c_void_p

_CFStringGetCString = CoreFoundation.CFStringGetCString
_CFStringGetCString.argtypes = [ c_void_p, c_char_p, c_uint, c_uint ]
_CFStringGetCString.restype = c_bool

kCFStringEncodingUTF8 = 0x08000100

# MAX_PATH on POSIX is usually 4096, so it should be enough
# It might be determined dynamically, but don't bother for now
MAX_PATH = 4096

result = []

paths = _NSSearchPathForDirectoriesInDomains(directory, domainMask, expand)

# CFArrayGetCount will crash if argument is NULL
# Even though NSSearchPathForDirectoriesInDomains never returns null, we'd better check it
if paths:
for i in range(0, _CFArrayGetCount(paths)):
path = _CFArrayGetValueAtIndex(paths, i)

buff = create_string_buffer(MAX_PATH)
if _CFStringGetCString(path, buff, sizeof(buff), kCFStringEncodingUTF8):
result.append(buff.raw.decode('utf-8').rstrip('\0'))
del buff

_CFRelease(paths)

return result

print NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask)

但是如果你只是使用 ~/Library 宇宙可能不会坍塌 ;)

关于python - 在 OS X 上,是否可以从纯 Python 获取用户库目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35099501/

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