Python3 configparser (配置解析)

Python3 configparser (配置解析)

時(shí)間:2019-05-18
環(huán)境:python3.7.3
官方文檔:https://docs.python.org/3/library/configparser.html?highlight=configparser#configparser.ConfigParser

1. 相關(guān)模塊引入

import configparser

2. 基礎(chǔ)使用

conf.ini 配置文件:

import configparser

configPath = './conf.ini'
conf = configparser.ConfigParser()

## 寫入
# conf['DEFAULT'] = {
#     'ServerAliveInterval': '45',
#     'Compression': 'yes',
#     'CompressionLevel': '9',
#     'ForwardX11': 'yes'
# }
# conf['MySQL'] = {
#     'host': 'localhost'
#     'port': '3306'
#     'username': 'root'
# }
# conf['domain.com'] = {
#     'Port': '50022',
#     'ForwardX11': 'no'
# }
# conf['DEFAULT']['ForwardX11'] = 'no'
# with open(configPath, 'w') as configfile:
#     conf.write(configfile)

## 讀取
conf.read(configPath)
print(conf.sections())        # ['MySQL', 'domain.com']
print('confItem' in conf)     # False
print('DEFAULT' in conf)      # True
print('MySQL' in conf)      # True
print(conf.get('MySQL', 'host'))  # localhost
print(int(conf['MySQL']['port']))

print('\n遍歷 MySQL 節(jié)點(diǎn) (同時(shí)遍歷了 DEFAULT 的配置)')
for key in conf['MySQL']:
    print(key + ' = ' + conf['MySQL'][key])

最終 conf.ini 配置文件內(nèi)容:

[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = no

[MySQL]
host = localhost
port = 3306
username = root

[domain.com]
port = 50022
forwardx11 = no

結(jié)論:

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

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

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