仅在更改时保存配置

2024-10-02 10:24:54 发布

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

是否可以添加一个检查,当生成的配置与移动的行相同时丢弃挂起的配置更改?你知道吗

我之所以这么问是因为在一些脚本中,每次关闭某个应用程序时,我都会保存配置,当我提交文件夹时,我总是会得到this之类的内容,而且我认为这是不必要的I/O加载。你知道吗

以下是我的loadCfg和saveCfg函数:

# I/O #
def loadCfg(path, cfg):
    """
    :param path:
    :param cfg:
    """
    if not os.path.isfile(path) or os.path.getsize(path) < 1:
        saveCfg(path, cfg)
    cfg = cfg.read(path, encoding='utf-8')

def saveCfg(path, cfg):
    """
    :param path:
    :param cfg:
    """
    with open(path, mode='w', encoding="utf-8") as cfgfile:
       cfg.write(cfgfile)

Tags: path脚本文件夹应用程序内容paramosdef
1条回答
网友
1楼 · 发布于 2024-10-02 10:24:54

首先让我说我怀疑不必要的I/O负载是否重要,您想做的很可能是过早优化的情况。你知道吗

也就是说,这里有一种方法似乎是可行的——尽管我还没有对它进行彻底的测试,也没有尝试将它合并到loadCfg()saveCfg()函数中。(其名称不遵循PEP 8 - Style Guide for Python Code推荐的函数命名约定,顺便说一句)。你知道吗

基本思想是将初始的ConfigParser实例转换为字典并保存它。然后,在关闭应用程序之前,再次执行此操作,并比较before和after字典以确定它们是否相同。你知道吗

from configparser import ConfigParser
import os


def as_dict(config):  # Utility function.
    """
    Converts a ConfigParser object into a dictionary.

    The resulting dictionary has sections as keys which point to a dict
    of the sections options as key => value pairs.

    From https://stackoverflow.com/a/23944270/355230
    """
    the_dict = {}

    for section in config.sections():
        the_dict[section] = {}
        for key, val in config.items(section):
            the_dict[section][key] = val

    return the_dict


def loadCfg(path, cfg):
    """
    :param path:
    :param cfg:
    """
    if not os.path.isfile(path) or os.path.getsize(path) < 1:
        saveCfg(path, cfg)
    cfg.read(path, encoding='utf-8')  # "read" doesn't return a value.


def saveCfg(path, cfg):
    """
    :param path:
    :param cfg:
    """
    with open(path, mode='w', encoding="utf-8") as cfgfile:
        cfg.write(cfgfile)


if __name__ == '__main__':

    # Create a config file for testing purposes.
    test_config = ConfigParser()
    test_config.add_section('Section1')
    test_config.set('Section1', 'an_int', '15')
    test_config.set('Section1', 'a_bool', 'true')
    test_config.set('Section1', 'a_float', '3.1415')
    test_config.set('Section1', 'baz', 'fun')
    test_config.set('Section1', 'bar', 'Python')
    saveCfg('example.cfg', test_config)

    # Read it back in.
    config = ConfigParser()
    loadCfg('example.cfg', config)

    before_dict = as_dict(config)  # Convert it to a dict and save.

    # Change it (comment-out next line to eliminate difference).
    config.set('Section1', 'an_int', '42')

    after_dict = as_dict(config)  # Convert possibly updated contents.

    # Only update the config file if contents of configparser is now different.
    if after_dict == before_dict:
        print('configuration not changed, config file not rewritten')
    else:
        print('configuration has changed, updating config file')
        saveCfg('example.cfg', config)

相关问题 更多 >

    热门问题