如何以跨平台方式存储Python桌面应用程序数据?
我有一个 python 桌面应用程序需要存储用户数据。 在 Windows 上,这通常位于 %USERPROFILE%\Application Data\AppName\
中,在 OSX 上,通常位于 ~/Library/Application Support/AppName/
中,在其他 *nix 上通常是~/.appname/
。
标准库中存在一个函数 os.path.expanduser 可以让我获得用户的主目录,但我知道至少在 Windows 上,“应用程序数据”已本地化为用户的语言。 对于 OSX 来说可能也是如此。
获取此位置的正确方法是什么?
更新: 一些进一步的研究表明,在 OSX 上获取此信息的正确方法是使用函数 NSSearchPathDirectory,但那是 Cocoa,所以这意味着调用 PyObjC 桥...
I have a python desktop application that needs to store user data. On Windows, this is usually in %USERPROFILE%\Application Data\AppName\
, on OSX it's usually ~/Library/Application Support/AppName/
, and on other *nixes it's usually ~/.appname/
.
There exists a function in the standard library, os.path.expanduser
that will get me a user's home directory, but I know that on Windows, at least, "Application Data" is localized into the user's language. That might be true for OSX as well.
What is the correct way to get this location?
UPDATE:
Some further research indicates that the correct way to get this on OSX is by using the function NSSearchPathDirectory, but that's Cocoa, so it means calling the PyObjC bridge...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,我讨厌自己回答自己的问题,但似乎没有人知道。 我把答案留给后人。
Well, I hate to have been the one to answer my own question, but no one else seems to know. I'm leaving the answer for posterity.
有一个小模块可以做到这一点:
https://pypi.org/project/appdirs/
There's a small module available that does exactly that:
https://pypi.org/project/appdirs/
您可以尝试使用 Qt 中的
QSettings
。 您可以通过以下方式获取 MyCompany/MyApp.ini 文件的路径:或者,在不更改任何全局状态的情况下:
在 Win7 上,您会得到类似以下内容:
在 Linux 上(可能有所不同):
我不知道 OSX 的可能结果(但是我想)。
QSettings
功能似乎很不错,直到您想使用registerFormat
为止,PySide 中不提供该功能,因此没有简单的方法可以使用 YAML 或 JSON 编写器进行设置。You can try to use
QSettings
from Qt. You can obtain the path to your MyCompany/MyApp.ini file this way:Alternatively, without changing any global state:
On Win7 you get something like:
On Linux (may vary):
I don't know the possible results for OSX (but I'd like to).
QSettings
functionallity seem to be nice until you want to useregisterFormat
, which is not available in PySide, so there is no easy way to use YAML or JSON writers for settings.那么,对于 Windows APPDATA(环境变量)指向用户的“应用程序数据”文件夹。 但不确定 OSX 是否如此。
在我看来,正确的方法是针对每个平台进行操作。
Well, for Windows APPDATA (environmental variable) points to a user's "Application Data" folder. Not sure about OSX, though.
The correct way, in my opinion, is to do it on a per-platform basis.