天天看点

python模块之ConfigParser:解析配置文件模块python模块之ConfigParser:解析配置文件模块

python模块之ConfigParser:解析配置文件模块

ConfigParser是一个简单易用的python解析配置文件的模块,可以从配置文件中解析出各section,各种类型的参数。

配置文件

# cat sample.conf

[numbers]
pi = 3.141592653
[messages]
greeting = Welcome to the area calculation program!
question = Please enter the radius:
result_message = The area is
           

解析代码

# cat parseconfig.py

#!/usr/bin/env python
import ConfigParser

CONFIGFILE = 'sample.conf'

config = ConfigParser.ConfigParser()
#Read config file
config.read(CONFIGFILE)

print config.get('messages', 'greeting')

radius = input(config.get('messages', 'question') + ' ')

print config.get('messages', 'result_message'),

print config.getfloat('numbers', 'pi') * radius**2