白日依山尽,黄河入海流。欲穷千里目,更上一层楼。 -- 唐·王之涣

Ansible系列-基础篇-配置文件Ini之Python版

欢迎关注个人公众号 DailyJobOps

源站地址 配置文件ini之python版


@toc

什么是ini配置文件

解释来自百度百科

ini 是 initialization的缩写,即初始化文件。最初出现在windows WIN3X,其主要是由 section和parameters组成,parameters是ini的基本组成单元,是由等号= 链接的键值对key=value,最常见比如PHP的配置文件格式就是ini格式

ini格式介绍

1、parameters

组成的基本单元,是由等号= 链接的键值对key=value,比如实际配置中

1
2
3
4
5
6
; 独立的parameter配置
demo_param = demo_value

[global]
mysql_host = 192.168.1.10
mysql_user = demouser

2、section

实际业务场景中,我们都会把某些parameters归属到一个分组,比如网站名称、网站关键字等归属到 global 分组,MySQL 主机、用户、端口等配置归属到 数据库分组;

这里的 global 分组 或者 数据库分组 在ini配置文件中对应的就是 section 概念

比如配置文件 demo.ini

1
2
3
4
5
6
7
8
9
10
11
12
13
; comments here
; demo_key = demo_value

[global]
site_name = colinspace website
site_url = http://blog.colinspace.com
site_keywords = ['colinspace', 'devops']

[database]
mysql_host = 192.168.1.10
mysql_user = demouser
mysql_password = demoPasswd
mysql_port = 3306

3、无section parameters会报错

如果某个parameter没有section,那么利用Python 的 configparser 模块解析的时候会直接报错,比如上面配置文件的中 demo_key = demo_value 就是没有属于的section,所以报错信息如下:

1
2
3
4
5
6
7
8
9
10
Traceback (most recent call last):
File "demo_ini.py", line 25, in <module>
cf.read_file(f)
File "/Users/demouser/.pyenv/versions/3.6.6/lib/python3.6/configparser.py", line 718, in read_file
self._read(f, source)
File "/Users/demouser/.pyenv/versions/3.6.6/lib/python3.6/configparser.py", line 1080, in _read
raise MissingSectionHeaderError(fpname, lineno, line)
configparser.MissingSectionHeaderError: File contains no section headers.
file: 'demo.ini', line: 2
'demo_key = demo_value\n'

4、注释信息

ini的注释使用 ; 分号,在想被注释的部分前面添加 分号; 即可,比如上面配置的中的

1
2
; comments here
; demo_key = demo_value

python 操作 ini 文件

ini 格式的文件后缀是没有要求的,可以是ini 或者其他,比如 cfg 、conf 等

一般对于ini的操作大概有以下:

  • 获取所有 section - cf.sections()
  • 检测某个section是否存在 - cf.has_section('section-name')
  • section 存在的时候获取该section下所有配置项items - cf.items('section-name')
  • section 存在的时候获取该section下都有哪些选项option - cf.options('section-name')
  • section 存在的时候,检测该section下是否存在某个option - cf.has_option('section-name', 'option-name')
  • section 存在的时候获取section下某个选项option的值 - cf.get('section-name', 'option-name')
  • 写入某些配置到 ini 文件 - cf.write(f)

这里先看demo脚本执行的结果,注意脚本的最后一行提示我们在 ini文件中写入了某些配置

1
2
3
4
5
6
7
8
(kfzdingoa) ➜  temp python demo_ini.py demo.ini
sections: ['global', 'database']
has section?: True
global section items: [('site_name', 'colinspace website'), ('site_url', 'http://blog.colinspace.com'), ('site_keywords', "['colinspace', 'devops']")]
global section options: ['site_name', 'site_url', 'site_keywords']
database section has mysql_user option? True
get mysql_user value from database section: demouser
==>Try to write some configurations into ini file<==

脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python
# encoding: utf-8
# Author: colinspace.com
# Desc: demo for python on ini file
#

import sys

# python3 中 configparser为小写和python2 不一样,所以做个判断导入
if sys.version_info.major == 2:
import ConfigParser as cfg
else:
import configparser as cfg

# 命令行输入需要解析的 ini 文件
if len(sys.argv) >= 2:
ini_file = sys.argv[1]
elif len(sys.argv) < 2:
print("Usage:")
print("\tscript.py ini_file")
sys.exit(5)

# 获取 ConfigParser
cf = cfg.ConfigParser()

# 读取 ini 相关配置
with open(ini_file, 'a') as f:
cf.read_file(f)
print("sections: ", cf.sections())
print("has section?: ", cf.has_section("global"))
print("global section items: ", cf.items("global"))
print("global section options: ", cf.options("global"))
print("database section has mysql_user option? ", cf.has_option("database", "mysql_user"))
print("get mysql_user value from database section: ", cf.get("database", "mysql_user"))

# 进行配置写入 ini 文件
print("==>Try to write some configurations into ini file<==")
cf["cache"] = {"redis_host": "192.168.1.11", "redis_port": 6379}
with open(ini_file, 'w') as f:
cf.write(f)

最后我们检查 demo.ini 文件,发现cache相关的配置成功写入文件

1
2
3
4
(kfzdingoa) ➜  temp tail -4 demo.ini
[cache]
redis_host = 192.168.1.11
redis_port = 6379

另外也可以动态的添加 添加、删除配置


与君共勉

作者

Colin

发布于

2021-12-08

许可协议