Python配置文件常用的方法

在日常开发小脚本时,经常要使用配置文件,以下是我在日常开发中总结的自己的常用的使用配置文件的方法:

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]}

函数根据提供的参数返回其中的数据组值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值