简体   繁体   English

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

[英]Load, Store and delete config parameters from file using pickle

I am trying to persist the state of my app and so far have found the pickle library.我正在尝试坚持我的应用程序的 state 并且到目前为止已经找到了泡菜库。

I found out how to set and get config parameters into a dictionary from When using Python classes as program configuration structures (which includes inherited class attributes), a good way to save/restore?我从When using Python classes as program configuration structure(包括继承的 class 属性)中找到了如何将配置参数设置和获取到字典中,这是保存/恢复的好方法?

I have managed to get it to save to an external config file but i don't think I'm doing it right and it all feels a bit clunky.我已经设法将其保存到外部配置文件中,但我认为我做得不对,而且感觉有点笨拙。

here is a cut down version to demo:这是演示的精简版本:

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应用程序.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()

This works the way I would expect it to however I do not know how to save the variable object name, instead the python generated name is stored in the config file, this is only OK if I only ever append more parameters but would mess everything up if I inserted a new parameter in between the existing ones.这可以按照我期望的方式工作,但是我不知道如何保存变量 object 名称,而是将 python 生成的名称存储在配置文件中,只有当我只使用 Z9516DFB15F51C7EE19A4D46B8C0DBE1 时才会有更多参数如果我在现有参数之间插入一个新参数。

example output of config file:配置文件的示例 output:

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

I would like to know if there is a better way of doing this?我想知道是否有更好的方法来做到这一点?

I think it is better if you give your parameters meaningful names by setting yourself the names of the variables instead of using the default ones:我认为最好通过设置变量的名称而不是使用默认名称来为参数命名有意义的名称:

eg例如

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

will give you the config会给你配置

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

So even if you change the order in which the variables are created, it will not change their names and you will still be able to retrieve the correct value in the config file.因此,即使您更改了变量的创建顺序,它也不会更改它们的名称,您仍然可以在配置文件中检索到正确的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM