[Python]使用Python中的config配置


Python中有ConfigParser類,可以很方便的從配置文件中讀取數據(如DB的配置,路徑的配置),所以可以自己寫一個函數,實現讀取config配置。

config文件的寫法比較簡單,[section]下配置key=value,一下是例子:db.conf

#配置數據庫
[database]
dbhost=127.0.0.1
dbport=3366
dbname=test
dbuser=test
dbpassword=test
dbcharset=utf8

接着寫一個讀取config的方法模塊

#encoding:utf-8
#name:mod_config.py

import ConfigParser
import os

#獲取config配置文件
def getConfig(section, key):
    config = ConfigParser.ConfigParser()
    path = os.path.split(os.path.realpath(__file__))[0] + '/db.conf'
    config.read(path)
    return config.get(section, key)

#其中 os.path.split(os.path.realpath(__file__))[0] 得到的是當前文件模塊的目錄

 

當需要在文件中讀取config的配置時,就載入這個模塊,調用getConfig方法。

import mod_config

dbname = mod_config.getConfig("database", "dbname")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM