python学习笔记3-解析配置文件ConfigParser模块

配置文件内容:

[db]
db_host=127.0.0.1
db_port=3306
db_user=root
db_pass=password
[concurrent]
thread=10
processor=20

如果遵循以上格式,那么就可以用python的ConfigParser模块。

#!/usr/bin/python
# Filename: parse_module.py

import ConfigParser

filename = 'my.conf'

parse = ConfigParser.ConfigParser()

parse.read(filename)

sections = parse.sections()

for i in sections:
    options = parse.options(i)
    values = parse.items(i)
    print "Section is %s " % i
    print "Options are %s " % options
    print "Values are %s " % values

输出:

Section is db 
Options are ['db_host', 'db_port', 'db_user', 'db_pass'] 
Values are [('db_host', '127.0.0.1'), ('db_port', '3306'), ('db_user', 'root'), ('db_pass', 'password')] 
Section is concurrent 
Options are ['thread', 'processor'] 
Values are [('thread', '10'), ('processor', '20')] 

但是如果配置文件中,parameter选项中含有[],则无法用此模块进行解析。。因此当试用python作为开发语言时,配置文件的格式可以选择符合configparser模块的格式。。。

下面的配置就无法使用configparser模块. 会将含有[]的部分当作section来解析。。。。

[db]
host[0]=127.0.0.1
host[1] = 192.168.1.123
db_port=3306
db_user=root
db_pass=password
[concurrent]
thread=10
processor=20


使用configparser模块解析配置文件时,发现的问题:

  1. 参数名称的大写全部会转换为小写。
  2. 参数名称不能含有[,]
  3. 如果含有多个名字相同的section时,会以最后一个section为准。


一个简单的读配置文件的代码,其中section部分相当与忽略了,而返回一个包含所有的参数的dict。

#!/usr/bin/python
# Filename: readConf.py

import ConfigParser

cofile = 'test2.properties'

def read_config_file(filename):
    '''Read_config_file(filename)

        this function is used for parse the config file'''    
    data = {}
    config = ConfigParser.ConfigParser()
    try:
        with open(filename,'r') as confile:
            config.readfp(confile)
        #config.read(filename)
            for i in config.sections():
                for (key, value) in config.items(i):
                    data[key] = value
            return data    
    except Exception:
        print "Open file error."

p = read_config_file(cofile)

如果有更简单或者更清晰的代码,欢迎大家指正。。。。。


还是发现了一个问题,如果不同的section中含有相同参数名字的参数,那个上面这个解析将无法判断出参数来自哪个section。

例如,myslq的配置文件中,client section和mysqld section中都含有socket和port这两个参数。如果用上面的代码,则无法判断哪个dict中的两个socket和port分别来自哪个section。。。


这样存放了之后,dict中的元素的先后顺序,和添加的顺序有不同。

你可能感兴趣的:(Linux)