[Python]ConfigParser解析配置文件

最近發現不少接口配置都硬編碼在souce file中了,因而就看了下python怎麼解析配置文件,重構下這一塊。python

這個應該是早就要做的。。。mysql

[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
skip-external-locking
old_passwords = 1
skip-bdb
skip-innodb
users = aa,bb,cc

[names]
n1 = lzz
n2 = orangle
n3 = zero


eg:sql

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#python2.7x
#config_parser.py  @2014-07-25
#author: orangleliu
'''
使用 ConfigParser 模塊來解析和寫入配置文件,主要支持的文件類型有鍵值對風格的配置和json格式的配置
簡單的配置應該能夠應付的了
'''

import ConfigParser

config = ConfigParser.RawConfigParser(allow_no_value=True)
config.read('conf.cfg')

#str
print config.get('mysqld', 'user')
#int
print config.getint('mysqld', 'old_passwords')
#list  一種解析方法
users = config.get('mysqld', 'users')
for i in  users.strip().split(','):
    print i

#list 另一種解析方法,放到section裏面
names = config.items("names")
for key, name in names:
    print key, name

print config.sections()
print config.has_section('default')

簡單的配置均可以知足的。json

相關文章
相關標籤/搜索