Python ConfigParser

Python ConfigParser (Python ConfigParser)

Python ConfigParser module is an extremely important one when it comes to creating configurable applications.

在创建可配置应用程序时,Python ConfigParser模块是一个非常重要的模块。

To provide a quick summary, using configparser module, we can keep the configuration related to our application in a configuration file, anywhere in the system and access it inside our application.

为了提供一个简短的摘要,使用configparser模块,我们可以将与我们的应用程序相关的配置保存在系统中任何位置的配置文件中,并在我们的应用程序内部对其进行访问。

So, if we suppose that we keep our database connection details in the config file, we just need to change them to make our application point to a completely new database. This means that we didn’t have to change anything in our application to do this!

python configparser

因此,如果假设我们将数据库连接详细信息保留在config文件中,则只需更改它们以使我们的应用程序指向一个全新的数据库。 这意味着我们不必在应用程序中进行任何更改即可!

配置文件可以包括什么? (What can config file include?)

Thie config files we create can contain integers, floating point values, and Booleans. Specifically, here are important points:

我们创建的配置文件可以包含整数,浮点值和布尔值。 具体来说,以下是要点:

  • The config file sections can be identified by having lines starting with [ and ending with ]. Between square brackets, we can put the section’s name, which can be any character except square bracket itself.

    可以通过以[开头和]结尾的行来标识配置文件部分。 在方括号之间,可以放置节的名称,该名称可以是除方括号本身以外的任何字符。
  • Lines starting with ; or # are treated as comments and are not available programmatically.

    行以;#被视为注释,无法通过编程方式使用。
  • The values are separated by a = or a :.

    这些值由一个分开=或一个:

Let’s look at a sample config file as well which will clear things well.

让我们也看一个示例配置文件,它将很好地清除所有内容。

# A comment which can contain anything.
[database_config]
url = https://localhost:3306/mysql/
username = root
; Consider hashing this password rather than
; keeping it as plain-text here
password = MY_PASSWORD

See, how easy was that! The values which can be used programmatically in above files are url, username and password.

瞧,那有多容易! 可以在上述文件中以编程方式使用的值为url,用户名和密码。

Python配置文件 (Python Config Files)

Let’s put these concepts into use with some code snippets.

让我们将这些概念与一些代码片段一起使用。

使用配置文件 (Using config files)

We will be creating a sample config file which looks like this:

我们将创建一个示例配置文件,如下所示:

# A comment which can contain anything.
[database_config]
url = https://localhost:3306/mysql/
username = root
; Consider hashing this password rather than
; keeping it as plain-text here
password = MY_PASSWORD

Make this file and name it database.config and keep it in the same directory as the program we write next:

创建此文件并将其命名为database.config ,并将其保存在与我们接下来编写的程序相同的目录中:

from configparser import ConfigParser

parser = ConfigParser()
parser.read('database.config')

print(parser.get('database_config', 'url'))

Here, we first find the section and then we continue to providing the exact key which we need. This is even good in terms of code readability. Let’s see the output for this program:

python configparser example

在这里,我们首先找到该部分,然后继续提供所需的确切密钥。 就代码可读性而言,这甚至是很好的。 让我们看一下该程序的输出:

This was pretty simple actually.

实际上,这非常简单。

检查配置文件是否存在 (Checking if config file exist)

Before using the key values in our program, it will always be better if we check if the config file exists at all. With this, we can integrate a much better error mechanism in our application and maybe, inform the user if config files are missing.

在程序中使用键值之前,最好先检查一下配置文件是否存在。 这样,我们可以在我们的应用程序中集成一个更好的错误机制,并且可能在配置文件丢失时通知用户。

Let’s see the code snippet:

让我们看一下代码片段:

from configparser import ConfigParser
import glob

config_parser = ConfigParser()

files_to_find = ['database.config', 'does-not-exist.config']

found_files = config_parser.read(files_to_find)
missing_files = set(files_to_find) - set(found_files)

print('Found config files:  ', sorted(found_files))
print('Missing files     :  ', sorted(missing_files))

Let’s see the output for this program:

python config file parser if exists

让我们看一下该程序的输出:

遍历所有存在的值 (Iterating over all values present)

We can iterate over all the sections and values present in the config files to look for a particular value or do any other operations.

我们可以遍历配置文件中存在的所有部分和值,以查找特定值或执行任何其他操作。

Let’s see the code snippet on how this can be done:

让我们看一下如何做到这一点的代码片段:

from configparser import ConfigParser

config_parser = ConfigParser()
config_parser.read('database.config')

for section_name in config_parser.sections():
    print('Section:', section_name)
    print('  Options:', config_parser.options(section_name))
    for key, value in config_parser.items(section_name):
        print('  {} = {}'.format(key, value))
    print()

Let’s see the output for this program:

python config files iterate properties

让我们看一下该程序的输出:

检查部分是否存在 (Checking if a section is present)

Wouldn’t it be better if we could just provide a section key and check if the section is present or not? It is possible actually and that’s what we will do in next code snippet:

如果我们只提供一个部分密钥并检查该部分是否存在,那会更好吗? 实际上是有可能的,这就是我们将在下一个代码段中执行的操作:

from configparser import ConfigParser

config_parser = ConfigParser()
config_parser.read('database.configdatabase.config')

for key in ['url', 'cluster-address', 'database_config']:
    print('{:<12}: {}'.format(key, config_parser.has_section(key)))

Let’s see the output for this program:

python configparser section exists

让我们看一下该程序的输出:

检查是否存在值 (Checking if a value is present)

Now, let’s directly check if the value is present or not. Let’s see the code snippet on how this can be done:

现在,让我们直接检查该值是否存在。 让我们看一下如何做到这一点的代码片段:

from configparser import ConfigParser

config_parser = ConfigParser()
config_parser.read('database.config')

find_sections = ['cluster-address', 'database_config']
find_options = ['url', 'some-option']

for section in find_sections:
    has_section = config_parser.has_section(section)
    print('{} section exists: {}'.format(section, has_section))
    for key in find_options:
        has_option = config_parser.has_option(section, key)
        print('{}.{:<12}  : {}'.format(section, key, has_option))
    print()

Let’s see the output for this program:

python config file example

让我们看一下该程序的输出:

结论 (Conclusion)

In this post, we saw how we can use Python‘s configparser module to access config files and put it to use in our application.

在本文中,我们看到了如何使用Python的configparser模块访问配置文件并将其用于我们的应用程序。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/18729/python-configparser

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值