使用Python中的config配置
阿新 • • 發佈:2021-09-08
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")