#! /usr/bin/env python
# -*- coding: UTF-8 -*-
# @Time : 2018/12/27 16:56
# @Author : [email protected]
# @Site :
# @File : processing.py
# @Software : PyCharm
import configparser
class ConfigReader(object):
def __init__(self, config_file):
self.cf = configparser.ConfigParser()
self.cf.read(config_file)
def read_config(self, name, key):
result = self.cf.get(name, key)
return result
# class Settings(object):
# def __init__(self, config_file):
# self.cf = configparser.ConfigParser()
# self.cf.read(config_file)
# for section in self.cf.sections():
# for option in self.cf.options(section):
# str = self.cf.get(section, option)
# setattr(self, option, str)
class Settings(object):
def __init__(self, config_file):
self.cf = configparser.ConfigParser()
self.cf.read(config_file)
for section in self.cf.sections(): # 读取所有的sections
for k, v in self.cf.items(section): # 读取每个section中的值(key, value)
setattr(self, k, v)
if __name__ == "__main__":
# 方式一
settings = Settings("config.ini")
print(settings.db_name) # 第一种读取方式
print(settings.cf.get('db', 'db_name')) # 第二种读取方式
# 方式二
config_reader = ConfigReader()
print config_reader.read_config('db', 'db_name') # 第三种读取方式
ini文件示例
[db]
db_host = 172.16.0.123
db_port = 3306
db_user = test
db_pass = test123
db_name = testdb
[saltstack]
url = https://192.168.63.13:8888
user = xiaoluo
pass = 123456
[network]
device = eth0