如何以跨平台方式为python存储桌面应用程序数据? [英] How do I store desktop application data in a cross platform way for python?

查看:176
本文介绍了如何以跨平台方式为python存储桌面应用程序数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要存储用户数据的python桌面应用程序。在Windows上,通常是%USERPROFILE%\Application Data\AppName\ ,在OSX上通常是〜/ Library / Application Support / AppName / ,在其他* nixes上通常是〜/ .appname /

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/.

标准库中有一个函数 os.path.expanduser ,它将为我提供用户的主目录,但我知道,至少在Windows上,应用程序数据已本地化为用户的语言。

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?

更新:
一些进一步的研究表明,在OSX上获取此信息的正确方法是使用功能NSSearchPathDirectory,但这就是Cocoa,因此它意味着调用PyObjC桥...

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

推荐答案

好吧,我不想成为回答我自己问题的人,但似乎没人知道。我留下后人的答案。

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.

APPNAME = "MyApp"
import sys
from os import path, environ
if sys.platform == 'darwin':
    from AppKit import NSSearchPathForDirectoriesInDomains
    # http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSearchPathForDirectoriesInDomains
    # NSApplicationSupportDirectory = 14
    # NSUserDomainMask = 1
    # True for expanding the tilde into a fully qualified path
    appdata = path.join(NSSearchPathForDirectoriesInDomains(14, 1, True)[0], APPNAME)
elif sys.platform == 'win32':
    appdata = path.join(environ['APPDATA'], APPNAME)
else:
    appdata = path.expanduser(path.join("~", "." + APPNAME))

这篇关于如何以跨平台方式为python存储桌面应用程序数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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