Python使用configparser庫讀取配置文件
這篇文章主要介紹了Python使用configparser庫讀取配置文件,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
背景:
在寫接口自動(dòng)化框架,配置數(shù)據(jù)庫連接時(shí),測(cè)試環(huán)境和UAT環(huán)境的連接信息不一致,這時(shí)可以將連接信息寫到conf或者cfg配置文件中
python環(huán)境請(qǐng)自行準(zhǔn)備。
python代碼直接封裝成類,方便其他模塊的引入。
from configparser import ConfigParser
class DoConfig:
def __init__(self,filepath,encoding='utf-8'):
self.cf = ConfigParser()
self.cf.read(filepath,encoding)
#獲取所有的section
def get_sections(self):
return self.cf.sections()
#獲取某一section下的所有option
def get_option(self,section):
return self.cf.options(section)
#獲取section、option下的某一項(xiàng)值-str值
def get_strValue(self,section,option):
return self.cf.get(section,option)
# 獲取section、option下的某一項(xiàng)值-int值
def get_intValue(self, section, option):
return self.cf.getint(section, option)
# 獲取section、option下的某一項(xiàng)值-float值
def get_floatValue(self, section, option):
return self.cf.getfloat(section, option)
# 獲取section、option下的某一項(xiàng)值-bool值
def get_boolValue(self, section, option):
return self.cf.getboolean(section, option)
def setdata(self,section,option,value):
return self.cf.set(section,option,value)
if __name__ == '__main__':
cf = DoConfig('demo.conf')
res = cf.get_sections()
print(res)
res = cf.get_option('db')
print(res)
res = cf.get_strValue('db','db_name')
print(res)
res = cf.get_intValue('db','db_port')
print(res)
res = cf.get_floatValue('user_info','salary')
print(res)
res = cf.get_boolValue('db','is')
print(res)
cf.setdata('db','db_port','3306')
res = cf.get_strValue('db', 'db_port')
print(res)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python 調(diào)試?yán)渲R(shí)(小結(jié))
這篇文章主要介紹了python 調(diào)試?yán)渲R(shí)(小結(jié)),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
python中類變量與成員變量的使用注意點(diǎn)總結(jié)
python 的類中主要會(huì)使用的兩種變量:類變量與成員變量。類變量是類所有實(shí)例化對(duì)象共有的,而成員變量是每個(gè)實(shí)例化對(duì)象自身特有的。下面這篇文章主要給大家介紹了在python中類變量與成員變量的一些使用注意點(diǎn),需要的朋友可以參考借鑒,下面來一起看看吧。2017-04-04
基于python SMTP實(shí)現(xiàn)自動(dòng)發(fā)送郵件教程解析
這篇文章主要介紹了基于python實(shí)現(xiàn)自動(dòng)發(fā)送郵件教程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
Python3的urllib.parse常用函數(shù)小結(jié)(urlencode,quote,quote_plus,unquot
這篇文章主要介紹了Python3的urllib.parse常用函數(shù),結(jié)合實(shí)例形式分析了urlencode,quote,quote_plus,unquote,unquote_plus等函數(shù)的相關(guān)使用技巧,需要的朋友可以參考下2016-09-09
深入淺出Python中三個(gè)圖像增強(qiáng)庫的使用
這篇文章主要帶大家了解一下Python中三個(gè)圖像增強(qiáng)庫的使用:Imgaug、Albumentations和SOLT,文中通過示例進(jìn)行了詳細(xì)介紹,需要的可以參考一下2022-05-05
Python Django 命名空間模式的實(shí)現(xiàn)
這篇文章主要介紹了Python Django 命名空間模式的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08

