python读取配置文件yaml

YAML:一种非标记语言,可以简单表达清单、列表等数据形态,文件后缀为 .yml

基本语法:

1.大小写敏感

2.使用缩进表示层级关系

3.缩进不允许使用tab,只允许空格,但是对空格数不要求

4.# 表示注释

数据类型

1.键值对

key: value  ":"和value之间应该有空格

# 字典 {'name': "test", 'age': 12}
name: test
age: 12

2.列表

# 列表 [1,2 ,3]
-1
-2
-3

3.复合结构

# 字典嵌套字典{'stud1': {'name': "test", 'age': 12}, 'stud2': {'name': "test2", 'age': 12}}
stud1:
  name: test
  age: 12
stud2:
  name: test2
  age:12
  
  
# 字典嵌套列表 {list1: [1,2,3], list2:[4,5,6]}
list1:
  -1
  -2
  -3
list2:
  -4
  -5
  -6
  
# 列表嵌套列表,[[1,2,3], [4,5,6]]
-
  -1
  -2
  -3
-
  -4
  -5
  -6

4.其他

a.引号

字符可以用单引号或者双引号或者不用,单引号会将字符内的特殊符号转义。eg. 'test test',输出是test test

双引号不会转义特殊符号

b.文本块 使用|标注的文本内容缩进表示的块,可以保留块中已有的换行符【存疑】

name: | 

  test

  test

输出果,会保留换行

name: | +

  test

  test

删除文字块末尾的换行

name: -

  test

  test

>将文字块中的回车替换成空格

name: >

  test

  test   

输出test test

c.引用

&表示复制数据的别名以及内容,*表示引用

name: &a test

age: *a

输出age=test

d.存量

布尔值: true、false或者TRUE或者True

数字:

12 整数

0b1010_0111 二进制

.inf 空值,无穷大

浮点数

1.2

1.2e+4 科学计数法

f.空值

null或者~表示

g.日期和时间

date:
- 2018-02-17 #日期必须使用ISO 8601格式,即yyyy-MM-dd
datetime:
- 2018-02-17T15:02:31+08:00 #时间使用ISO 8601格式,时间和日期之间使用T连接,最后使用+代表时区

h.强制类型转换

单个感叹号表示强制转换数据类型,通常是自定义类型,双叹号是内置类型转换。

age: !!str

12

pyyaml

官网下载pyyaml安装,或者使用pip安装。

1.写文件

dict1 = {"oppo_findx2pro": {'platformName': "Android",
                      'platFormVersion': "10",
                      'deviceName': "dd",
                      'udid': "648d4f29",
                      'automationName': "UiAutomator2",
                      'noReset': False,
                      'unicodeKeyboard': True,
                      'resetKeyboard': True,
                      'appPackage': "com.tencent.mm",
                      'appActivity': "com.tencent.mm.ui.LauncherUI",
                      'autoGrantPermissions': True,
                      'chromedriverExecutable': r"C:Usersv_yddchenDesktopchromedriver_win32 77.0chromedriver.exe",
                      'chromeOptions': {'androidProcess': "com.tencent.mm:toolsmp"}}
             }
    with open('test_dict.yaml', 'w', encoding='utf-8') as f:
        yaml.dump(dict1, f)
def dump(data, stream=None, Dumper=Dumper, **kwds):
    """
    Serialize a Python object into a YAML stream.
    If stream is None, return the produced string instead.
    """
    return dump_all([data], stream, Dumper=Dumper, **kwds)

2.读文件

def load(stream, Loader=None):
    """
    Parse the first YAML document in a stream
    and produce the corresponding Python object.
    """
    if Loader is None:
        load_warning('load')
        Loader = FullLoader

    loader = Loader(stream)
    try:
        return loader.get_single_data()
    finally:
        loader.dispose()

代码实现

def read_dict_yaml():
    with open('test_dict.yaml', 'r', encoding='utf-8') as f:
        print(yaml.load(f.read()))

错误和警告

yaml.load()如果参数Loader使用默认值的话会报错:YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.

官网解释:https://msg.pyyaml.org/load 

pyyaml提供了safe_load函数,该函数可以加载yam的子集。

或者使用Loader声明加载器。

BaseLoader 基本加载器,加载最基本的YAML

SafeLoader 安全地加载YAML语言的子集,建议加载不信任的输入

FullLoader 加载完整的YAML语言,避免执行任意代码(这是当前pyyaml 5.1在发出警告后调用的默认加载程序)

UnsafeLoder 也成为向后兼容的Loader【存疑】

原文地址:https://www.cnblogs.com/Cc905/p/13434633.html