第14章-配置者

配置文件供用户和程序员使用。它们通常用于存储应用程序的设置,甚至操作系统的设置。python的核心库包含一个名为configparser的模块,您可以使用该模块创建配置文件并与之交互。在本章中,我们将花几分钟的时间学习它是如何工作的。

创建配置文件

使用configparser创建配置文件非常简单。让我们创建一些代码来演示:

import configparser

def createConfig(path):
    """
    Create a config file
    """
    config = configparser.ConfigParser()
    config.add_section("Settings")
    config.set("Settings", "font", "Courier")
    config.set("Settings", "font_size", "10")
    config.set("Settings", "font_style", "Normal")
    config.set("Settings", "font_info",
               "You are using %(font)s at %(font_size)s pt")

    with open(path, "w") as config_file:
        config.write(config_file)


if __name__ == "__main__":
    path = "settings.ini"
    createConfig(path)

上面的代码将创建一个配置文件,其中一个部分标记为“设置”,其中包含四个选项:字体、字体大小、字体样式和字体信息。还要注意,在python 3中,我们只需要指定以只写模式写入文件,即“w”。回到python 2,我们不得不使用“wb”以二进制模式编写。

如何读取、更新和删除选项

现在我们已经准备好学习如何读取配置文件,更新其选项,甚至如何删除选项。在这种情况下,通过实际编写一些代码更容易学习!只需将以下函数添加到上面编写的代码中即可。

import configparser
import os

def crudConfig(path):
    """
    Create, read, update, delete config
    """
    if not os.path.exists(path):
        createConfig(path)

    config = configparser.ConfigParser()
    config.read(path)

    # read some values from the config
    font = config.get("Settings", "font")
    font_size = config.get("Settings", "font_size")

    # change a value in the config
    config.set("Settings", "font_size", "12")

    # delete a value from the config
    config.remove_option("Settings", "font_style")

    # write changes back to the config file
    with open(path, "w") as config_file:
        config.write(config_file)


if __name__ == "__main__":
    path = "settings.ini"
    crudConfig(path)

此代码首先检查配置文件的路径是否存在。如果没有,那么它使用我们之前创建的createConfig函数来创建它。接下来,我们创建一个configParser对象,并将配置文件路径传递给它进行读取。要读取配置文件中的选项,我们调用configParser对象的 get 方法,将节名称和选项名称传递给它。这将返回选项的值。如果要更改选项的值,则使用 set 方法,传递节名称、选项名称和新值。最后,您可以使用 remove_option 方法删除选项。

在示例代码中,我们将字体大小的值更改为 12 我们完全删除了字体样式选项。然后我们将更改写回磁盘。

这并不是一个很好的例子,因为你永远不应该有一个像这个函数一样做任何事情的函数。所以让我们把它分成一系列函数:

import configparser
import os

def create_config(path):
    """
    Create a config file
    """
    config = configparser.ConfigParser()
    config.add_section("Settings")
    config.set("Settings", "font", "Courier")
    config.set("Settings", "font_size", "10")
    config.set("Settings", "font_style", "Normal")
    config.set("Settings", "font_info",
               "You are using %(font)s at %(font_size)s pt")

    with open(path, "w") as config_file:
        config.write(config_file)


def get_config(path):
    """
    Returns the config object
    """
    if not os.path.exists(path):
        create_config(path)

    config = configparser.ConfigParser()
    config.read(path)
    return config


def get_setting(path, section, setting):
    """
    Print out a setting
    """
    config = get_config(path)
    value = config.get(section, setting)
    msg = "{section} {setting} is {value}".format(
        section=section, setting=setting, value=value)
    print(msg)
    return value


def update_setting(path, section, setting, value):
    """
    Update a setting
    """
    config = get_config(path)
    config.set(section, setting, value)
    with open(path, "w") as config_file:
        config.write(config_file)


def delete_setting(path, section, setting):
    """
    Delete a setting
    """
    config = get_config(path)
    config.remove_option(section, setting)
    with open(path, "w") as config_file:
        config.write(config_file)



if __name__ == "__main__":
    path = "settings.ini"
    font = get_setting(path, 'Settings', 'font')
    font_size = get_setting(path, 'Settings', 'font_size')

    update_setting(path, "Settings", "font_size", "12")

    delete_setting(path, "Settings", "font_style")

与第一个例子相比,这个例子被重构了很多。我甚至用pep8来命名函数。每个函数都应该是自解释和自包含的。我们不将所有逻辑放在一个函数中,而是将其分离为多个函数,然后在底部if语句中演示它们的功能。现在您可以导入模块并自己使用它。

请注意,这个例子有硬编码的部分,所以您需要进一步更新这个例子,使其完全通用。

如何使用插值

ConfigParser模块还允许 插值 ,这意味着您可以使用一些选项来构建另一个选项。我们实际上使用字体信息选项来实现这一点,因为它的值基于字体和字体大小选项。我们可以使用python字典更改内插值。让我们花点时间来证明这两个事实。

import configparser
import os

def interpolationDemo(path):
    if not os.path.exists(path):
        createConfig(path)

    config = configparser.ConfigParser()
    config.read(path)

    print(config.get("Settings", "font_info"))

    print(config.get("Settings", "font_info",
                     vars={"font": "Arial", "font_size": "100"}))


if __name__ == "__main__":
    path = "settings.ini"
    interpolationDemo(path)

如果运行此代码,则应看到类似以下内容的输出:

You are using Courier at 12 pt
You are using Arial at 100 pt

总结

在这一点上,你应该对 配置共享器 您可以将其用于自己的项目的功能。还有一个项目叫 ConfigObj 这不是您可能还想签出的Python的一部分。 ConfigObj配置分析器 .但是如果你手头紧,或者你的组织不允许第三方软件包,那么 配置分析器 很可能符合要求。