配置文件内容:


[plain] view plain copy

[db]  

db_host=127.0.0.1  

db_port=3306  

db_user=root  

db_pass=password  

[concurrent]  

thread=10  

processor=20  


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

[python] view plain copy

#!/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  

输出:


[plain] view plain copy

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模块的格式。。。