仅在更改后保存配置

时间:2018-08-12 11:43:14

标签: python python-3.x configparser

是否有可能添加一条检查,以使即使配置的行可能已经移动,但最终的配置仍相同时,仍丢弃待更改的配置?

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

1 个答案:

答案 0 :(得分:2)

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

也就是说,这是一种可行的方法-尽管我尚未对其进行全面测试或试图将其合并到您的loadCfg()saveCfg()函数中。 (其名称不遵循PEP 8 - Style Guide for Python Code建议的函数命名约定BTW)。

基本思想是将初始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 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)