Home  >  Article  >  Backend Development  >  Detailed introduction to the ConfigParser module

Detailed introduction to the ConfigParser module

零下一度
零下一度Original
2017-07-23 13:45:121567browse

1. Introduction

Used to generate and modify common configuration documents. The name of the current module was changed to configparser in the python 3.x version.

2. Configuration file format

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no

 

3. Create configuration file

import configparser

# 生成一个处理对象
config = configparser.ConfigParser()  
#默认配置 
config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

#生成其他的配置组
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'

config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'  # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here

config['DEFAULT']['ForwardX11'] = 'yes'

#写入配置文件
with open('example.ini', 'w') as configfile:
    config.write(configfile)

 

4. Read the configuration file

1. Read the node information

import configparser

config = configparser.ConfigParser()
config.read('example.ini')

# 读取默认配置节点信息
print(config.defaults())

#读取其他节点
print(config.sections())

# 输出
OrderedDict([('compression', 'yes'), ('serveraliveinterval', '45'), ('compressionlevel', '9'), ('forwardx11', 'yes')])

['bitbucket.org', 'topsecret.server.com']

 

2. Determine whether the configuration node name exists

print('ssss' in config)
print('bitbucket.org' in config)

#输出
False
True

 

3. Read the information in the configuration node

print(config['bitbucket.org']['user'])

#输出

hg

 

4. Loop to read all the information of the configuration node

for key in config['bitbucket.org']:
    print(key, ':', config['bitbucket.org'][key])

#输出

user : hg
compression : yes
serveraliveinterval : 45
compressionlevel : 9
forwardx11 : yes

 

The above is the detailed content of Detailed introduction to the ConfigParser module. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn