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': ['[email protected]', '[email protected]'], 'phone': [1111111, 2222222, 3333333]}
        return config.get(section)

2. 使用示例

YAML能夠解析以下格式文件:

mail:
 - xx@zz.cn
 - yy@zz.cn

phone:
 - 1111111
 - 2222222
 - 3333333

yaml解析後生成字典,內部數據組成一個數組:

{'mail': ['[email protected]', '[email protected]'], 'phone': [1111111, 2222222, 3333333]}

函數根據提供的參數返回其中的數據組值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章