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")

