Ansible系列-基礎(chǔ)篇-配置文件Ini之Python版

歡迎關(guān)注個(gè)人公眾號 DailyJobOps

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

什么是ini配置文件

解釋來自百度百科

ini 是 initialization的縮寫,即初始化文件。最初出現(xiàn)在windows WIN3X,其主要是由 section和parameters組成,parameters是ini的基本組成單元,是由等號= 鏈接的鍵值對key=value,最常見比如PHP的配置文件格式就是ini格式

ini格式介紹

1、parameters

組成的基本單元,是由等號= 鏈接的鍵值對key=value,比如實(shí)際配置中

; 獨(dú)立的parameter配置
demo_param = demo_value

[global]
mysql_host = 192.168.1.10
mysql_user = demouser

2、section

實(shí)際業(yè)務(wù)場景中,我們都會把某些parameters歸屬到一個(gè)分組,比如網(wǎng)站名稱、網(wǎng)站關(guān)鍵字等歸屬到 global 分組,MySQL 主機(jī)、用戶、端口等配置歸屬到 數(shù)據(jù)庫分組;

這里的 global 分組 或者 數(shù)據(jù)庫分組 在ini配置文件中對應(yīng)的就是 section 概念

比如配置文件 demo.ini

; 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會報(bào)錯(cuò)

如果某個(gè)parameter沒有section,那么利用Python 的 configparser 模塊解析的時(shí)候會直接報(bào)錯(cuò),比如上面配置文件的中 demo_key = demo_value 就是沒有屬于的section,所以報(bào)錯(cuò)信息如下:

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的注釋使用 ; 分號,在想被注釋的部分前面添加 分號; 即可,比如上面配置的中的

; comments here
; demo_key = demo_value

python 操作 ini 文件

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

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

  • 獲取所有 section - cf.sections()
  • 檢測某個(gè)section是否存在 - cf.has_section('section-name')
  • section 存在的時(shí)候獲取該section下所有配置項(xiàng)items - cf.items('section-name')
  • section 存在的時(shí)候獲取該section下都有哪些選項(xiàng)option - cf.options('section-name')
  • section 存在的時(shí)候,檢測該section下是否存在某個(gè)option - cf.has_option('section-name', 'option-name')
  • section 存在的時(shí)候獲取section下某個(gè)選項(xiàng)option的值 - cf.get('section-name', 'option-name')
  • 寫入某些配置到 ini 文件 - cf.write(f)

這里先看demo腳本執(zhí)行的結(jié)果,注意腳本的最后一行提示我們在 ini文件中寫入了某些配置

(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<==

腳本

#!/usr/bin/env python
# encoding: utf-8
# Author: colinspace.com
# Desc: demo for python on ini file
#

import sys

# python3 中 configparser為小寫和python2 不一樣,所以做個(gè)判斷導(dǎo)入
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 相關(guān)配置
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"))

# 進(jìn)行配置寫入 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 文件,發(fā)現(xiàn)cache相關(guān)的配置成功寫入文件

(kfzdingoa) ?  temp tail -4 demo.ini
[cache]
redis_host = 192.168.1.11
redis_port = 6379

另外也可以動(dòng)態(tài)的添加 添加、刪除配置


與君共勉
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容