天天看點

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