如何在Python中存储变量/首选项以供以后使用

Par*_*ker 8 python registry preferences persistent

我正在使用Python for Windows的程序,并希望保存变量和用户首选项,以便即使在程序终止并重新启动后我也可以调用它们.

有没有理想的方法在Windows机器上执行此操作?是否_winreg和Windows注册表适合这项任务?或者我是否需要创建自己的某种数据库?

War*_* P 7

Python2在Python3中有ConfigParser,它是configparser:

import ConfigParser, os

config = ConfigParser.ConfigParser()
config.readfp(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
Run Code Online (Sandbox Code Playgroud)

即使在Windows上,你应该知道注册表是一个可怜的浮渣和恶意的蜂巢,你不应该用它来存储你的python应用程序配置.

  • `你应该知道注册表是一个可怜的渣滓和恶棍的蜂巢.这是你应该从这整个问题中取得的最重要的事情. (8认同)

Jos*_*iah 5

您通常希望将其存储在“home”文件夹中的配置文件夹中。这在 *nix 系统上很容易,在 windows 中更难,因为您实际上需要获取“应用程序数据”目录。这通常对我有用:

import os
if os.name != "posix":
    from win32com.shell import shellcon, shell
    homedir = "{}\\".format(shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0))
else:
    homedir = "{}/".format(os.path.expanduser("~"))
Run Code Online (Sandbox Code Playgroud)

拥有主目录后,您应该创建一个以您的项目命名的文件夹:

if not os.path.isdir("{0}.{1}".format(homedir,projectname)):
    os.mkdir("{0}.{1}".format(homedir,projectname))
Run Code Online (Sandbox Code Playgroud)

然后,您可以在该文件夹中创建一个配置文件,并以您选择的格式将您的选项写入其中(我个人最喜欢的是 XML)。

  • @Josiah,为什么不使用 os.path.join 方法而不是根据文件系统显式指定正斜杠或反斜杠? (2认同)