仅在更改时保存配置

Only save config if changed

是否可以添加一个检查,当生成的配置相同时丢弃待处理的配置更改,即使移动的行可能已经移动?

我问是因为在某些脚本中,我每次关闭某些应用程序时都会保存配置,当我提交我的文件夹时,我总是会得到类似 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)

首先让我说我怀疑不必要的 I/O 负载问题,你想做的可能是过早优化的情况。

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

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

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 
    """
    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)