Python的配置文件


配置文件

setting.ini文件是一个纯文本
[DataBase1]
username = admin
passwors = root [DataBase2]
hostname = 127.0.0.1
port = 3306

这是一般配置文件的常见的格式,[]里面叫做Section部分的名称,整个[]以及下面的每一项(每一个key=value,叫做Option)都是一个Section区域

Python读取配置文件

#引入依赖库,Python2.x引入ConfigParser Python3.x引入configparser
try:
import ConfigParser as cReader
except Exception as reason:
import configparser as cReader

要实现的功能

# -*- coding:utf-8 -*-
"""
自定义配置文件读取库
调用ConfigParser,只实现常用功能,作为学习ConfigParser和自用库
""" #引入依赖库,Python2.x引入ConfigParser Python3.x引入configparser
import json
try:
import ConfigParser as cReader
except Exception as reason:
import configparser as cReader #定义类和函数
class ConfigChannel:
"""建立配置读取类""" def __init__(self, configFile):
"""建立ConfigChannel对象"""
try:
self.configFile = configFile
self.channel = cReader.SafeConfigParser()
self.channel.read(open(configFile))
except Exception as reason:
raise def getOption(self, Section, Option):
"""获取某区域的某一项配置"""
try:
return self.channel.getfloot(Section, Option)
except Exception as reason:
try:
return self.channel.getint(Section, Option)
except Exception as reason:
try:
return self.channel.getboolean(Section, Option)
except Exception as reason:
return self.channel.get(Section, Option) def hasOption(self, Section, Option):
"""判断是否存在这个Option"""
try:
return self.channel.has_option(Section, Option)
except Exception as reason:
raise def showOptions(self):
"""展示所有Options"""
try:
return self.channel.options()
except Exception as reason:
raise def setOption(self, Section, Option, Value):
"""会写或增加配置某区域某一项配置"""
try:
self.channel.set(Section, Option, Value)
self.channel.write(open(self.configFile, "w"))
except Exception as reason:
raise def rmvOption(self, Section, Option):
"""删除某一个配置项"""
try:
self.channel.remove_option(Section, Option)
self.channel.write(open(self.configFile, "w"))
except Exception as reason:
raise def hasSection(self, Section):
"""判断是否存在这个Section"""
try:
return self.channel.has_section(Section)
except Exception as reason:
raise def showOptions(self):
"""展示所有Sections"""
try:
return self.channel.sections()
except Exception as reason:
raise def addSection(self, Section):
"""增加一个配置区域"""
try:
self.channel.add_section(Section)
self.channel.write(open(self.configFile, "w"))
except Exception as reason:
raise def rmvSection(self, Section):
"""删除一个配置区域"""
try:
self.channel.remove_section(Section)
self.channel.write(open(self.configFile, "w"))
except Exception as reason:
raise def getConfigFromString(self, string):
"""从字符串读取配置并写入"""
try:
_dictionary = json.loads(string)
return self.getConfigFromDictionary(_dictionary)
except Exception as reason:
pass
try:
configList = string.split(":")
if len(configList) != 3 or '' in configList:
raise Exception
Section = configList[0]
Option = configList[1]
Value = configList[2]
if self.hasSection(Section):
self.setOption(Section, Option, Value)
else:
self.addSection(Section)
self.setOption(Section, Option, Value)
except Exception as reason:
raise def getConfigFromDictionary(self, dictionary):
"""从字典读取配置并写入"""
if not isinstance(dictionary, dict):
raise
try:
for key in dictionary:
if not isinstance(dictionary.get(key), dict):
continue
if not self.channel.hasSection(key):
self.addSection(key)
for subkey in dictionary[key]:
self.channel.setOption(key, subkey,
dictionary[key][subkey])
except Exception as reason:
raise

熟悉使用ConfigParser库读写配置文件的更多相关文章

  1. Python自动化测试 -ConfigParser模块读写配置文件

    C#之所以容易让人感兴趣,是因为安装完Visual Studio, 就可以很简单的直接写程序了,不需要做如何配置. 对新手来说,这是非常好的“初体验”, 会激发初学者的自信和兴趣. 而有些语言的开发环 ...

  2. python:实例化configparser模块读写配置文件

    之前的博客介绍过利用python的configparser模块读写配置文件的基础用法,这篇博客,介绍下如何实例化,方便作为公共类调用. 实例化的好处有很多,既方便调用,又降低了脚本的维护成本,而且提高 ...

  3. python:利用configparser模块读写配置文件

    在自动化测试过程中,为了提高脚本的可读性和降低维护成本,将一些通用信息写入配置文件,将重复使用的方法写成公共模块进行封装,使用时候直接调用即可. 这篇博客,介绍下python中利用configpars ...

  4. 用ConfigParser模块读写配置文件——Python

    对于功能较多.考虑用户体验的程序,配置功能是必不可少的,如何存储程序的各种配置? 1)可以用全局变量,不过全局变量具有易失性,程序崩溃或者关闭之后配置就没了,再者配置太多,将变量分配到哪里也是需要考虑 ...

  5. Python自动化测试 (二) ConfigParser模块读写配置文件

    ConfigParser 是Python自带的模块, 用来读写配置文件, 用法及其简单. 直接上代码,不解释,不多说. 配置文件的格式是: []包含的叫section,    section 下有op ...

  6. configparser模块读写ini配置文件

    在自动化测试过程中,为了提高脚本的可读性和降低维护成本,将一些通用信息写入配置文件,将重复使用的方法写成公共模块进行封装,使用时候直接调用即可. 这篇博客,介绍下python中利用configpars ...

  7. ConfigParser 读写配置文件

    一.ini: 1..ini 文件是Initialization File的缩写,即初始化文件,是windows的系统配置文件所采用的存储格式 2.ini文件创建方法: (1)先建立一个记事本文件.(2 ...

  8. Python-通过configparser读写配置文件

    Python读写配置文件: 1.创建配置文件(文件名以.conf或.ini结束的文件表示配置文件) 2.导入所需模块 OS, configparser >>> import os & ...

  9. python利用ConfigParser读写配置文件

    ConfigParser 是Python自带的模块, 用来读写配置文件, 用法非常简单. 配置文件的格式是: []包含的叫section,    section 下有option=value这样的键值 ...

随机推荐

  1. 内存与cpu的关系

    CPU是负责运算和处理的,内存是交换数据的.当程序或者操作者对CPU发出指令,这些指令和数据暂存在内存里,在CPU空闲时传送给CPU,CPU处理后把结果输出到输出设备上,输出设备就是显示器,打印机等. ...

  2. 使用nginx反向代理解决前端跨域问题

    1. 首先去Nginx官网下载一个最新版本的Nginx,下载地址:http://nginx.org/en/download.html.我这里下载的版本是:nginx/Windows-1.12.0.下载 ...

  3. 自定义控件?试试300行代码实现QQ侧滑菜单

    Android自定义控件并没有什么捷径可走,需要不断得模仿练习才能出师.这其中进行模仿练习的demo的选择是至关重要的,最优选择莫过于官方的控件了,但是官方控件动辄就是几千行代码往往可能容易让人望而却 ...

  4. 【Math】矩阵求导

    https://en.wikipedia.org/wiki/Matrix_calculus http://blog.sina.com.cn/s/blog_7959e7ed0100w2b3.html

  5. 马尔科夫链蒙特卡洛(Markov chain Monte Carlo)

    (学习这部分内容大约需要1.3小时) 摘要 马尔科夫链蒙特卡洛(Markov chain Monte Carlo, MCMC) 是一类近似采样算法. 它通过一条拥有稳态分布 \(p\) 的马尔科夫链对 ...

  6. [OpenCV] Image Processing - Grayscale Transform & Histogram

    颜色直方图 首先,先介绍一些Hist的基本使用. Ref:[OpenCV]数字图像灰度直方图 官方文档:https://docs.opencv.org/trunk/d8/dbc/tutorial_hi ...

  7. instsrv.exe srvany.exe启动服务

    1.通过注册表注册服务 private static readonly string regpath = @"SYSTEM\CurrentControlSet\Services\Consul ...

  8. 【RF库Collections测试】Remove Duplicates

    Name:Remove DuplicatesSource:Collections <test library>Arguments:[ list_ ]Returns a list witho ...

  9. using 释放内存的写法

    using (FileStream fileStream = File.Open(fileName,FileMode.Open,FileAccess.Read,FileShare.ReadWrite) ...

  10. AddComponentRecursively

    class AddComponentRecursively extends ScriptableWizard { var componentName : String = ""; ...