Appium+Python:使用标准库configparser读取config或ini配置文件

写在前面:没有

前提:再编写appium脚本过程中,某个元素id、class可能在多个文件中使用,当界面发生变化的时候,脚本将变得难以维护,因此使用configparser提高Appium脚本的复用性、可配置性。

1、config 或ini文件格式

config 配置文件由两部分组成sections与items 。sections 用来区分不同的配置块items 是sections下面的键值

config中括号[]中的为sections ,每个sections 可以有多个items。

[login_element]    ##sections值

username=usernameid        ##item值

password=passwordid

[course_element]    ##setions值

course=price          ##item值

2、Configparser基础

python 对于配置文件的读取已经标准化,标准库为configparser。引入包

from ConfigParser import ConfigParser

实例化

config = ConfigParser()

3、读取config文件数据

常用方法:

config = ConfigParser()  实例化对象

config.read(filename,encoding) 直接读取ini文件内容,finlename 文件地址,encoding 文件编码格式(可以为空)

config.sections() 得到所有的section,并以列表的形式返回

config.options(section) 得到该section的所有option

config.items(section) 得到该section的所有键值对

config[section][option] 读取section中的option的值

config.get(section,option) 得到section中option的值,返回为string类型

config.getint(section,option) 得到section中option的值,返回为int类型

config.getboolean(section,option) 得到section中option的值,返回为bool类型

config.getfloat(section,option) 得到section中option的值,返回为float类型

4、项目中的实际应用

a:新建一个config.ini配置文件:将element的元素或其它配置信息放进来

    eg:

[login_element]    ##sections值

username=usernameid        ##item值

password=passwordid

[course_element]    ##setions值

course=price          ##item值

b:使用Python configparser读取配置文件:

    from Configparser import Configparser

    cfg=Configparser()##实例化

    cfg.read(’filename’)

c:读取option

      cfg.get(‘sections’,’options’)


可能出现的问题及解决方法:

a:from Configparser import Configparser:提示无configparser;pip或pycharm手动安装或导入configparser模块。

b: cfg.read(’filename’):若filename不在同一个包名下面,会提示文件找不到,可以导入绝对路径+文件名:

如:cfg.read('/Users/amy/PycharmProjects/test001/config/config.ini')

你可能感兴趣的:(Appium+Python:使用标准库configparser读取config或ini配置文件)