使用pickle从文件中加载、存储和删除配置参数

2024-09-23 22:18:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试保持我的应用程序的状态,到目前为止,我已经找到了pickle库

我了解了如何从When using Python classes as program configuration structures (which includes inherited class attributes), a good way to save/restore?设置配置参数并将其放入字典

我已经设法将它保存到一个外部配置文件中,但我认为我做得不对,而且感觉有点笨重

以下是要演示的精简版本:

Config.py

# https://stackoverflow.com/questions/50613665/when-using-python-classes-as-program-configuration-structures-which-includes-in

import pickle
from pathlib import Path

filename = 'config'

class Config(dict):
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__
    
    def __init__(self):
        # Load config from file 
        my_file = Path(filename)

        if my_file.is_file():
            infile = open(filename, 'rb')
            self.update(pickle.load(infile))
            infile.close()    

    def __getstate__(self):
        return self

    def __setstate__(self, state):
        self.update(state)

    def save(self):
        # filename = 'config'  
        outfile = open(filename, 'wb')
        pickle.dump(self, outfile)
        outfile.close() 

App.py

import tkinter as tk
import pickle
from Config import Config

class App(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)

        # Init config
        self.config = Config()
         
        # initalise variables from config
        param0 = tk.BooleanVar()
        self.getConfig(param0)

        param1 = tk.StringVar()
        self.getConfig(param1)

        param2 = tk.StringVar()
        self.getConfig(param2, "one")

        # Build config page   
        cb = tk.Checkbutton(self, text = "Param", variable=param0)
        cb.pack()
        
        e = tk.Entry(self, textvariable=param1)
        e.pack()
        
        om = tk.OptionMenu(self, param2, "one", "two", "three")
        om.pack()

    def getConfig(self, object, default=None):
        if str(object) in self.config:
            object.set(self.config[str(object)])
        else:
            if default:
                object.set(default)
        object.trace("w", lambda name, index, mode, object=object: self.setConfig(object))
        
    def setConfig(self, object):
        self.config[str(object)] = object.get()

        self.config.save()       

if __name__ == "__main__":
    app=App()
    app.mainloop()

这是我期望的工作方式,但是我不知道如何保存变量对象名,而是python生成的名称存储在配置文件中,只有在我只追加更多参数时才行,但如果我在现有参数之间插入新参数,就会把一切搞得一团糟

配置文件的输出示例:

{'PY_VAR0': False, 'PY_VAR1': 'test string', 'PY_VAR2': 'three'}

我想知道有没有更好的方法


Tags: fromimportselfconfig参数ifobjectdef
1条回答
网友
1楼 · 发布于 2024-09-23 22:18:47

我认为最好通过设置变量的名称而不是使用默认名称来为参数指定有意义的名称:

例如

    param0 = tk.BooleanVar(name='boolean_param')
    param1 = tk.StringVar(name='string_param')
    param2 = tk.StringVar(name='user_choice')

我会给你配置文件

{'string_param': 'test string', 'boolean_param': False, 'user_choice': 'three'}

因此,即使您更改了变量的创建顺序,也不会更改它们的名称,并且您仍然能够在配置文件中检索到正确的值

相关问题 更多 >