python解析配置文件
python2.x:
import ConfigParser
python3.x:
import configparser
odoorpc.conf
[db]
db_host=127.0.0.1
db_port=3306
db_user=root
db_pass=password
[concurrent]
thread=10
processor=20
test.py
# -*- encoding: utf-8 -*-
import ConfigParser as configparser # py2 是ConfigParser
# import configparser # py3 是configparser
import string, os, sys
cf = configparser.ConfigParser()
cf.read("./odoorpc.conf")
# 返回所有的section
s = cf.sections()
print('section: %s' % s)
# out: section: ['db', 'concurrent']
o = cf.options("db")
print('options:[options: ['db_host', 'db_port', 'db_user', 'db_pass']
v = cf.items("db")](options: ['db_host', 'db_port', 'db_user', 'db_pass']v = cf.items("db")) %s' % o)
# out: options: ['db_host', 'db_port', 'db_user', 'db_pass']
v = cf.items("db")
print('db: %s' % v)
# out: db: [('db_host', '127.0.0.1'), ('db_port', '3306'), ('db_user', 'root'), ('db_pass', 'password')]
v = dict(cf.items("db"))
print('db: %s' % v)
# out: db: {'db_pass': 'password', 'db_user': 'root', 'db_host': '127.0.0.1', 'db_port': '3306'}
- sections():
- 或者配置文件所有的父节点
- options("db"):
- 获取父节点
db
下的节点名称
- 获取父节点
- items("db"):
- 获取父节点
db
下的信息,格式为[(key, value),(key1, value1)]
- 获取父节点