日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python生成配置文件config_Python configparser模块封装及构造配置文件

發(fā)布時(shí)間:2024/7/19 python 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python生成配置文件config_Python configparser模块封装及构造配置文件 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1.configparser模塊簡介

使用配置文件來靈活的配置一些參數(shù)是一件很常見的事情,配置文件的解析并不復(fù)雜,在python里更是如此,在官方發(fā)布的庫中就包含有做這件事情的庫,那就是configParser

configParser解析的配置文件的格式比較象ini的配置文件格式,就是文件中由多個section構(gòu)成,每個section下又有多個配置項(xiàng)

2.看一下configparser生成的配置文件的格式

ini配置文件格式如下:

這里是注釋

[log]

log_path = base_dir/OutPut/log/

[image]

img_path = base_dir/OutPut/image/

[report]

report_path = base_dir/OutPut/report/

[test_case]

test_case_path = base_dir/TestData/case.xlsx

3.讀取文件內(nèi)容

import configparser

import os

import sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

if sys.platform == "win32":

ENV_CONF_DIR = os.path.join(BASE_DIR, 'Common/conf/env_config.ini').replace('/', '\\')

else:

ENV_CONF_DIR = os.path.join(BASE_DIR, 'Common/conf/env_config.ini')

class Config(object):

def __init__(self, path):

self.path = path #配置文件名

self.cf = configparser.ConfigParser() #創(chuàng)建一個配置文件對象

self.cf.read(self.path, encoding='utf-8') # 調(diào)用配置文件對象的讀取方法,并傳入一個配置文件名

def get(self, field, key): # 獲取字符串類型的選項(xiàng)值

result = ""

try:

result = self.cf.get(field, key)

except:

result = ""

return result

def set(self, field, key, value):

try:

self.cf.set(field, key, value)

self.cf.write(open(self.path, 'w'))#創(chuàng)建一個配置文件并將獲取到的配置信息使用配置文件對象的寫入方法進(jìn)行寫入

except:

return False

return True

def r_config(config_file_path, field, key):

rf = configparser.ConfigParser()

try:

rf.read(config_file_path, encoding='utf-8')

if sys.platform == "win32":

result = rf.get(field, key).replace('base_dir', str(BASE_DIR)).replace('/', '\\')

else:

result = rf.get(field, key).replace('base_dir', str(BASE_DIR))

except:

sys.exit(1)

return result

def w_config(config_file_path, field, key, value):

wf = configparser.ConfigParser()

try:

wf.read(config_file_path)

wf.set(field, key, value)

wf.write(open(config_file_path, 'w'))

except:

sys.exit(1)

return True

if __name__ == '__main__':

print(r_config(ENV_CONF_DIR, 'log', 'log_path'))

print(r_config(ENV_CONF_DIR, 'DB', 'database'))

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。

本文標(biāo)題: Python configparser模塊封裝及構(gòu)造配置文件

本文地址: http://www.cppcns.com/jiaoben/python/331696.html

總結(jié)

以上是生活随笔為你收集整理的python生成配置文件config_Python configparser模块封装及构造配置文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。