av一区二区在线观看_亚洲男人的天堂网站_日韩亚洲视频_在线成人免费_欧美日韩精品免费观看视频_久草视

您的位置:首頁技術文章
文章詳情頁

Python configparser模塊常用方法解析

瀏覽:96日期:2022-07-24 18:40:17

ConfigParser模塊在python中用來讀取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一個或多個節(section), 每個節可以有多個參數(鍵=值)。使用的配置文件的好處就是不用在程序員寫死,可以使程序更靈活。

注意:在python 3 中ConfigParser模塊名已更名為configparser

configparser函數常用方法:

讀取配置文件:

read(filename) #讀取配置文件,直接讀取ini文件內容

sections() #獲取ini文件內所有的section,以列表形式返回[’logging’, ’mysql’]

options(sections) #獲取指定sections下所有options ,以列表形式返回[’host’, ’port’, ’user’, ’password’]

items(sections) #獲取指定section下所有的鍵值對,[(’host’, ’127.0.0.1’), (’port’, ’3306’), (’user’, ’root’), (’password’, ’123456’)]

get(section, option) #獲取section中option的值,返回為string類型>>>>>獲取指定的section下的option <class ’str’> 127.0.0.1

getint(section,option) 返回int類型getfloat(section, option) 返回float類型getboolean(section,option) 返回boolen類型

舉例如下:

配置文件ini如下:

[logging]level = 20path =server =

[mysql]host=127.0.0.1port=3306user=rootpassword=123456

注意,也可以使用:替換=

代碼如下:

import configparserfrom until.file_system import get_init_pathconf = configparser.ConfigParser()file_path = get_init_path()print(’file_path :’,file_path)conf.read(file_path)sections = conf.sections()print(’獲取配置文件所有的section’, sections)options = conf.options(’mysql’)print(’獲取指定section下所有option’, options)items = conf.items(’mysql’)print(’獲取指定section下所有的鍵值對’, items)value = conf.get(’mysql’, ’host’)print(’獲取指定的section下的option’, type(value), value)

運行結果如下:

file_path : /Users/xxx/Desktop/xxx/xxx/xxx.ini獲取配置文件所有的section [’logging’, ’mysql’]獲取指定section下所有option [’host’, ’port’, ’user’, ’password’]獲取指定section下所有的鍵值對 [(’host’, ’127.0.0.1’), (’port’, ’3306’), (’user’, ’root’), (’password’, ’123456’)]獲取指定的section下的option <class ’str’> 127.0.0.1

綜合使用方法:

import configparser'''讀取配置文件信息'''class ConfigParser(): config_dic = {} @classmethod def get_config(cls, sector, item): value = None try: value = cls.config_dic[sector][item] except KeyError: cf = configparser.ConfigParser() cf.read(’settings.ini’, encoding=’utf8’) #注意setting.ini配置文件的路徑 value = cf.get(sector, item) cls.config_dic = value finally: return valueif __name__ == ’__main__’: con = ConfigParser() res = con.get_config(’logging’, ’level’) print(res)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 在线观看日本网站 | 亚洲国产成人精品久久久国产成人一区 | 婷婷二区| 亚洲欧美激情精品一区二区 | 国产免费观看久久黄av片涩av | 国产精品美女久久久久aⅴ国产馆 | 美女天天操 | 女同久久另类99精品国产 | 成年人国产在线观看 | 一区二区手机在线 | 超碰在线人人干 | 波波电影院一区二区三区 | 久久91精品国产 | 日本精品一区二区三区在线观看视频 | 久草免费在线视频 | 国产精品美女在线观看 | 欧美在线亚洲 | 欧美成人在线免费 | 99re视频在线| 情侣酒店偷拍一区二区在线播放 | 99色综合| 91精品国产色综合久久不卡98口 | 国产精品自拍av | 国产一区免费 | 免费看日韩视频 | 国产亚洲精品精品国产亚洲综合 | 国产在线视频一区 | 精品国产一区二区三区日日嗨 | 国产传媒视频在线观看 | 久久久性色精品国产免费观看 | 久久91精品久久久久久9鸭 | 国产中文字幕在线观看 | 福利精品在线观看 | 97精品视频在线观看 | 91干b| 午夜影院在线观看 | 久久精品中文 | 久久久123| 久久久国产一区二区三区四区小说 | 亚洲久视频 | 中国一级毛片免费 |