Python配置文件常用的方法
2017-03-08 16:38
447 查看
在日常开发小脚本时,经常要使用配置文件,以下是我在日常开发中总结的自己的常用的使用配置文件的方法:
yaml解析后生成字典,内部数据组成一个数组:
函数根据提供的参数返回其中的数据组值。
config.conf
1. 核心用法
def get_config(self, section, key): config = ConfigParser.ConfigParser() path = os.path.split(os.path.realpath(__file__))[0] + '/config.conf' config.read(path) return config.get(section, key)
2. 使用示例
这个应该是我最常用的方案,python自带了ConfigParser,能够解析以下格式文件:# ./config.conf [api_filter_db] dbhost = xxx.xxx.xxx.xxx dbport = 3306 dbname = yyy dbuser = root dbpassword = zzz dbcharset = utf8 [mshow_db] dbhost = xxx.xxx.xxx.xxx dbport = 3306 dbname = yyy dbuser = root dbpassword = zzz dbcharset = utf8
# ./get_config.py
class Utils(object):
def get_config(self, section, key): config = ConfigParser.ConfigParser() path = os.path.split(os.path.realpath(__file__))[0] + '/config.conf' config.read(path) return config.get(section, key)
#可以引用get_config函数
class DoSomething(Utils):
conn = MySQLdb.connect(
host=self.get_config('api_filter_db', 'dbhost'),
port=int(self.get_config('api_filter_db', 'dbport')),
user=self.get_config('api_filter_db', 'dbuser'),
passwd=self.get_config('api_filter_db', 'dbpassword'),
db=self.get_config('api_filter_db', 'dbname'),
charset=self.get_config('api_filter_db', 'dbcharset')
)
cursor = conn.cursor()
YAML
YAML也是一种比较常用的配置文件方案,平时用ansible会用的比较多,要解析yaml文件,需要安装一个第三方的包:yaml# pip install yaml
1. 核心用法
# ./get_config.py class Utils(object): def get_config_yaml(self, section): path = os.path.split(os.path.realpath(__file__))[0] + '/config.yaml' config = yaml.load(file(config)) # {'mail': ['xx@zz.cn', 'yy@zz.cn'], 'phone': [1111111, 2222222, 3333333]} return config.get(section)
2. 使用示例
YAML能够解析以下格式文件:mail: - xx@zz.cn - yy@zz.cn phone: - 1111111 - 2222222 - 3333333
yaml解析后生成字典,内部数据组成一个数组:
{'mail': ['xx@zz.cn', 'yy@zz.cn'], 'phone': [1111111, 2222222, 3333333]}
函数根据提供的参数返回其中的数据组值。
相关文章推荐
- 加载Spring配置文件常用的三种方法
- 加载spring配置文件的常用三种方法
- Python3读取文件常用方法实例分析
- Python实现配置文件备份的方法
- python文件目录操作常用方法总结
- 加载spring配置文件的常用三种方法
- Mod_python 访问时不访问特定py文件的配置方法
- Python3写入文件常用方法实例分析
- Python读写配置文件的方法
- python分割文件的常用方法
- 加载spring配置文件的常用三种方法
- 在python的WEB框架Flask中使用多个配置文件的解决方法
- python 读取配置文件方法
- Python3读取文件常用方法实例分析
- 加载spring配置文件的常用三种方法
- python创建子进程,以及读取配置文件方法
- python下载文件的几种常用方法
- 在Python常用模块I如何打开相关文件的方法
- 在python的WEB框架Flask中使用多个配置文件的解决方法
- python读写ini配置文件方法实例分析