一、python使用自带的configparser模块用来读取配置文件,使用之前需要先导入该模块。
基础读取配置文件
-read(filename) 直接读取文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option
-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数
基础写入配置文件
write(fp)将config对象写入至某个 .ini 格式的文件Write an .ini-format representation of the configuration state.add_section(section)添加一个新的section
set( section, option, value 对section中的option进行设置,需要调用write将内容写入配置文件
remove_section(section)删除某个 section
remove_option(section, option)删除某个 section 下的 option
1、先创建config.ini文件
2、创建一个readconfig.py文件,读取配置文件信息
1 importconfigparser2 from base.path importconfig_dir3
4 classReadConfig:5 def __init__(self):6 configpath = config_dir(fileName='case_data.ini') #配置文件的路径
7 self.conf =configparser.RawConfigParser()8 self.conf.read(configpath,encoding='utf-8') #读取配置文件
9
10 defget_case_data(self,param):11 '''返回配置文件中具体的信息'''
12 value = self.conf.get('test_data',param) #获得具体的配置信息
13 returnvalue14
15 if __name__ == '__main__':16
17 test =ReadConfig()18 t = test.get_case_data("username")19 print(t,type(t))
3、写入配置文件
1 importconfigparser2 importos3
4 os.chdir("D:\\Python_config")5 cf =configparser.ConfigParser()6
7 #add section / set option & key
8 cf.add_section("test")9 cf.set("test", "count", 1)10 cf.add_section("test1")11 cf.set("test1", "name", "aaa")12
13 #write to file
14 with open("test2.ini","w+") as f:15 cf.write(f)
4、修改配置文件中的内容,一定要read()
1 importconfigparser2 importos3
4 os.chdir("D:\\Python_config")5 cf =configparser.ConfigParser()6
7 #modify cf, be sure to read!
8 cf.read("test2.ini")9 cf.set("test", "count", 2) #set to modify
10 cf.remove_option("test1", "name")11
12 #write to file
13 with open("test2.ini","w+") as f:14 cf.write(f)
二、YAML 是专门用来写配置文件的语言,非常简洁和强大,远比 JSON 格式方便。YAML在python语言中有PyYAML安装包。
1、首先需要安装:pip install pyyaml
2、它的基本语法规则如下:
1、大小写敏感
2、使用缩进表示层级关系
3、缩进时不允许使用Tab键,只允许使用空格。
4、缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
5、# 表示注释,从这个字符一直到行尾,都会被解析器忽略,这个和python的注释一样
YAML 支持的数据结构有三种:
1、对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
2、数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
3、纯量(scalars):单个的、不可再分的值。字符串、布尔值、整数、浮点数、Null、时间、日期
3、具体实例:
(1)dict类型 key:value
1 appname: xxxxxxxx.apk2 noReset: True3 autoWebview: Ture4 appPackage: xxxxxxxxx5 appActivity: xxxxxxxxxxx6 automationName: UiAutomator27 unicodeKeyboard: True #是否使用unicodeKeyboard的编码方式来发送字符串
8 resetKeyboard: True #是否在测试结束后将键盘重设系统默认的输入法
9 newCommandTimeout: 120
(2) dict套dict类型
1 info1:2 user:admin3 pwd:111111
4
5 info2:6 user2:admin7 pwd2:111111
(3)list类型 前面加上‘-’符号,且数字读出来的是int 或者float
1 -admin: 111111
2 -host : 222222
(4) 纯量 纯量:最基本、不可再分的值。
1 1、数值直接以字面量的形式表示2 number: 12.30 #{'number': 12.3}
3
4 2、布尔值用true和false表示5 isSet: true #{'isSet': True}
6 isSet1: false #{'isSet1': False}
7
8 3、null用~表示9 parent: ~ #{'parent': None}
10
11 4、时间采用 ISO8601 格式12 time1: 2001-12-14t21:59:43.10-05:00
13 #{'time1': datetime.datetime(2001, 12, 15, 2, 59, 43, 100000)}
14
15 5、日期采用复合 iso8601 格式的年、月、日表示16 date: 2017-07-31
17 #{'date': datetime.date(2017, 7, 31)}
18
19 6、YAML 允许使用两个感叹号,强制转换数据类型20 int_to_str: !!str 123
21 bool_to_str: !!str true #{'bool_to_str': 'true'}
(5)数组
1 1、数组可以采用行内表示法2 animal: [Cat, Dog]3 #打印结果:{'animal': ['Cat', 'Dog']}
4
5 2、一组连词线开头的行,构成一个数组6 animal1: - Cat - Dog -Goldfish7 #打印结果:{'animal1': ['Cat', 'Dog', 'Goldfish']}
(6)复合类型
list嵌套dict:
1 -user : admin2 pwd : '123456'
3 -user : host4 pwd : '111111'
其打印结果:
dict 嵌套list:
group1:-admin- '123456'group2:-host- '1111111'
其打印结果:
(7)字符串
1 默认不使用引号表示,也可以用单引号和双引号进行表示。2 but双引号不会对特殊转义字符进行转义。3 单引号中若还有单引号,必须连续使用两个单引号转义4
5 1、字符串默认不使用引号表示6 str1: 这是一个字符串7
8 2、如果字符串之中包含空格或特殊字符,需要放在引号之中。9 str2: '内容:*字符串'
10
11 3、单引号和双引号都可以使用,双引号不会对特殊字符转义。12 str3: '内容\n字符串'
13 str4: "content\n string"
14
15 4、单引号之中如果还有单引号,必须连续使用两个单引号转义。16 s3: 'labor''s day'
17
18 5、字符串可以写成多行,从第二行开始,必须有一个单空格缩进。换行符会被转为空格19 strline: 这是一段20 多行21 字符串22
23 6、多行字符串可以使用|保留换行符,也可以使用>折叠换行24 this: |
25 Foo26 Bar27 that: >
28 Foo29 Bar30
31 7、+表示保留文字块末尾的换行,-表示删除字符串末尾的换行。32 s4: |
33 Foo434 s5: |+
35 Foo536 s6: |-
37 Foo638 s7: |
39 Foo7
(8)对象
1 1、对象的一组键值对,使用冒号结构表示。2 animal: pets3 #打印结果:{'animal': 'pets'}
4
5 2、Yaml 也允许另一种写法,将所有键值对写成一个行内对象6 dict1: { name: Steve, foo: bar }7 #打印结果:{'dict1': {'foo': 'bar', 'name': 'Steve'}}
4、Python代码实现读取yaml文件
1 importyaml2 from base.public importyanml_dir3
4 defappium_desired():5 '''
6 启动app7 :return: driver8 '''
9 logging.info("============开始启动app===========")10 with open(yanml_dir('driver.yaml'),'r',encoding='utf-8') as file : #encoding='utf-8'解决文件中有中文时乱码的问题
11 data = yaml.load(file) #读取yaml文件
12 desired_caps ={}13 desired_caps['platformName'] = data['platformName']14 desired_caps['deviceName'] = data['deviceName']15 desired_caps['platformVersion'] = data['platformVersion']16 desired_caps['appPackage'] = data['appPackage']17 desired_caps['appActivity'] = data['appActivity']18 desired_caps['noReset'] = data['noReset']19 desired_caps['automationName'] = data['automationName']20 desired_caps['unicodeKeyboard'] = data['unicodeKeyboard']21 desired_caps['resetKeyboard'] = data['resetKeyboard']22 desired_caps['newCommandTimeout'] = data['newCommandTimeout']23 driver = webdriver.Remote('http://'+str(data['ip'])+':'+str(data['port'])+'/wd/hub',desired_caps)24 logging.info("===========app启动成功=============")25 driver.implicitly_wait(5)26 return driver
5、Python代码实现写入yaml文件
1 importyaml2 from base.path importconfig_dir3 yamlPath = config_dir(fileName='config.yaml')4
5 defsetYaml():6 '''写入yaml文件中,a 追加写入,w 覆盖写入'''
7 data ={8 "cookie1": {'domain': '.yiyao.cc', 'expiry': 1521558688.480118, 'httpOnly': False, 'name': '_ui_', 'path': '/',9 'secure': False, 'value': 'HSX9fJjjCIImOJoPUkv/QA=='}}10 with open(yamlPath,'a',encoding='utf-8') as fw:11 yaml.dump(data,fw)12
13 if __name__ == '__main__':14 setYaml()