Python 读取配置文件和yaml文件

  一、python使用自带的configparser模块用来读取配置文件,使用之前需要先导入该模块,具体操作如下:

1、先创建config.ini文件

  

2、创建一个readconfig.py文件,读取配置文件信息

 1 import configparser
 2 from base.path import config_dir
 3 
 4 class ReadConfig:
 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     def get_case_data(self,param):
11         '''返回配置文件中具体的信息'''
12         value = self.conf.get('test_data',param)   #获得具体的配置信息
13         return value
14 
15 if __name__ == '__main__':
16 
17     test = ReadConfig()
18     t = test.get_case_data("username")
19     print(t,type(t))

二、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.apk
2 noReset: True
3 autoWebview: Ture
4 appPackage: xxxxxxxxx
5 appActivity: xxxxxxxxxxx
6 automationName: UiAutomator2
7 unicodeKeyboard: True      # 是否使用unicodeKeyboard的编码方式来发送字符串
8 resetKeyboard: True        # 是否在测试结束后将键盘重设系统默认的输入法
9 newCommandTimeout: 120

  (2) dict套dict类型  

1 info1:
2       user:admin
3       pwd:111111
4       
5 info2:
6       user2:admin
7       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 - Goldfish 
7 # 打印结果:{'animal1': ['Cat', 'Dog', 'Goldfish']}

  (6)复合类型  

    list嵌套dict:

1 - user : admin
2   pwd  : '123456'
3 - user : host
4   pwd  : '111111'

其打印结果:
image.png

  • dict 嵌套list:
group1:
    - admin
    - '123456'
group2:
    - host 
    - '1111111'

其打印结果:
image.png

  (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   Foo
26   Bar
27 that: >
28   Foo
29   Bar
30   
31 7、+表示保留文字块末尾的换行,-表示删除字符串末尾的换行。
32 s4: |
33   Foo4
34 s5: |+
35   Foo5
36 s6: |-
37   Foo6
38 s7: |
39   Foo7

  (8)对象

1 1、对象的一组键值对,使用冒号结构表示。
2 animal: pets 
3 # 打印结果:{'animal': 'pets'}
4 
5 2、Yaml 也允许另一种写法,将所有键值对写成一个行内对象
6 dict1: { name: Steve, foo: bar } 
7 # 打印结果:{'dict1': {'foo': 'bar', 'name': 'Steve'}}

  4、Python代码实现读取yaml文件

 1 import yaml
 2 from base.public import yanml_dir
 3 
 4 def appium_desired():
 5     '''
 6     启动app
 7     :return: driver
 8     '''
 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 import yaml
 2 from base.path import config_dir
 3 yamlPath = config_dir(fileName='config.yaml')
 4 
 5 def setYaml():
 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()

猜你喜欢

转载自www.cnblogs.com/wang-rong/p/11416922.html