python config.ini的應用

來源:互聯網
上載者:User

標籤:輸入   python   bin   parse   class   有一個   div   getpath   sql   

  config.ini檔案的結構是以下這樣的:結構是"[ ]"之下是一個section,一部分一部分的結構。以下有三個section,分別為section0,section1,section2

[mysql config]host=127.0.0.1port=8080username=rootpassword=123456[online config]online=www.online.comusername=peixmpassword=123qwe[test config]test=www.test.comusername=peixmpassword=123qwe

那麼,怎麼在代碼中擷取到這些內容呢?

首先,要有一個config.ini檔案

#!/usr/bin/env/python# -*-coding:utf-8-*-# authour:xiapmin_peiimport configparser,os#封裝一個路徑,直接輸入檔案名稱filename就可以獲得filename的路徑def getPath(filename):    return os.path.join(os.path.dirname(__file__),os.pardir,‘data‘,filename)class Config(object):    def __init__(self,filename,section):        """        :param filename: 檔案名稱        :param section: 屬於檔案中的第幾個section,這是整形        """        self.section = section        #執行個體化一個configparser對象        self.cf = configparser.ConfigParser()        #讀取檔案的內容        self.cf.read(getPath(filename))    def getconfig(self,avg):        """        獲得想要屬性的內容        :param avg: 屬性名稱        :return: 屬性的值        """        print self.cf.sections()        parameter =self.cf.get(self.cf.sections()[self.section],avg)        return parameterif __name__=="__main__":    #執行個體化Config,想要config.ini檔案,第2個section的內容    con = Config("config.ini",1)    #擷取online這個屬性的值    print con.getconfig(‘online‘)

執行結果:由此可見,sections是一個列表

[‘mysql config‘, ‘online config‘, ‘test config‘]
www.online.com

Process finished with exit code 0

 

python config.ini的應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.