python封裝configparser模組擷取conf.ini值(最佳化版)

來源:互聯網
上載者:User

標籤:預設   key   技術分享   init   找不到   結果   模組   執行個體   read   

  昨天晚上封裝了configparser模組,是根據keyname擷取的value。python封裝configparser模組擷取conf.ini值

  我原本是想通過config.ini檔案中的section和keyname擷取value的,前兩天怎麼都調試不通過。今天百度了一下,有人通過字典的方式把我的和這個想法實現了,我把這個例子修改了一下,代碼如下,並通過測試,以後可以用在自動化測試架構中:

 1 #coding:utf-8 2 import os 3 import ConfigParser 4  5 class Dictionary(dict): 6     ‘‘‘ 7     把config.ini中的參數添加值dict 8     ‘‘‘ 9     def __getattr__(self, keyname):10         #如果key值不存在則返回預設值"not find config keyname"11         return self.get(keyname, "config.ini中沒有找到對應的keyname")12 13 class Config(object):14     ‘‘‘15     ConfigParser二次封裝,在字典中擷取value16     ‘‘‘17     def __init__(self):18         # 設定conf.ini路徑19         current_dir = os.path.dirname(__file__)20         top_one_dir = os.path.dirname(current_dir)21         file_name = top_one_dir + "\\conf\\conf.ini"22         # 執行個體化ConfigParser對象23         self.config = ConfigParser.ConfigParser()24         self.config.read(file_name)25         #根據section把key、value寫入字典26         for section in self.config.sections():27             setattr(self, section, Dictionary())28             for keyname, value in self.config.items(section):29                 setattr(getattr(self, section), keyname, value)30 31     def getconf(self, section):32         ‘‘‘33         用法:34         conf = Config()35         info = conf.getconf("main").url36         ‘‘‘37         if section in self.config.sections():38             pass39         else:40             print("config.ini 找不到該 section")41         return getattr(self, section)42 43 if __name__ == "__main__":44     conf = Config()45     info = conf.getconf("main").url46     print info

運行結果:

 conf.ini檔案

 

 

python封裝configparser模組擷取conf.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.