最近开始使用Python3.x,所有今后无特殊说明,Python代表的就是Python3.x ,最近在看代码时发现有人用Yaml —— Yet Another Markup Language :另一种标记语言,好奇,就拿来试试。希望后续的项目中可以尝试实践一下。
编程免不了要写配置文件,怎么写配置也是一门学问。
YAML 是专门用来写配置文件的语言,非常简洁和强大,远比 JSON 格式方便。
YAML在python语言中有PyYAML安装包。
YAML 语言(发音 /ˈjæməl/ )的设计目标,就是方便人类读写。它实质上是一种通用的数据串行化格式。
它的基本语法规则如下:
1、大小写敏感
2、使用缩进表示层级关系
3、缩进时不允许使用Tab键,只允许使用空格。
4、缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
5、#
表示注释,从这个字符一直到行尾,都会被解析器忽略,这个和python的注释一样
YAML 支持的数据结构有三种:
1、对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
2、数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
3、纯量(scalars):单个的、不可再分的值。字符串、布尔值、整数、浮点数、Null、时间、日期
1、环境搭建
执行命令:pip install pyyaml
这里主要是记录一下YAML在Python语言中的应用。类比于json库,yaml库与其有惊人的相似之处。一个load方法,一个dump方法。顾名知义,也比较的好理解。
新建一个配置文件信息:config.yaml
EMAIL:
Smtp_Server: smtp.mxhichina.com
Smtp_Sender: [email protected]
Password: 123456
OnLine_Receiver: [email protected]
Pre_Receiver: [email protected]
Test_Receiver: [email protected]
Msg_Title: 自动化测试
Content_Type: application/octet-stream
Text_sescription: API用列执行
resultPath: html/body/div[1]/p[4]
on-off: on
DB:
host: xxx
port: 3306
user: weibospider
password: xxx
db_name: weibo
db_type: mysql
3、代码实现获取配置文件信息
__author__ = 'Administrator'
import yaml
import sys,os
# 获取当前文件路径 F:/python项目/LoggerTest
file_path = os.path.dirname(__file__)
print(file_path)
# 获取当前文件的Realpath F:\python项目\LoggerTest
fileNamePath = os.path.split(os.path.realpath(__file__))[0]
print(fileNamePath)
# 获取配置文件的路径 F:\python项目\LoggerTest\config.yaml
yamlPath = os.path.join(fileNamePath,"config.yaml")
print(yamlPath)
# 加上 ,encoding='utf-8',处理配置文件中含中文出现乱码的情况。
f = open(yamlPath,"r",encoding="utf-8")
cont = f.read()
x= yaml.load(cont)
print(type(x))
print(x)
print("*********")
print(x['DB'])
print(type(x['DB']))
print(x['EMAIL'])
print(type(x['EMAIL']))
print("*********")
print(x['EMAIL']['Smtp_Server'])
print(type(x['EMAIL']['Smtp_Server']))
print("********")
print(x.get('DB').get('host'))
print(type(x.get('DB')))
4、代码实现写入配置文件
__author__ = 'Administrator'
import yaml
import sys,os
# 获取当前文件路径 F:/python项目/LoggerTest
file_path = os.path.dirname(__file__)
print(file_path)
# 获取当前文件的Realpath F:\python项目\LoggerTest
fileNamePath = os.path.split(os.path.realpath(__file__))[0]
print(fileNamePath)
# 获取配置文件的路径 F:\python项目\LoggerTest\config.yaml
yamlPath = os.path.join(fileNamePath,"config.yaml")
print(yamlPath)
# 写入yaml 文件,a 追加写入,w,覆盖写入
f = open(yamlPath,"a",encoding="utf-8")
#构建数据
data ={
"cookie1":{'domain': '.yiyao.cc', 'expiry': 1521558688.480118, 'httpOnly': False, 'name': '_ui_', 'path': '/', 'secure': False, 'value': 'HSX9fJjjCIImOJoPUkv/QA=='}
}
#装载数据
yaml.dump(data,f)
# 读取数据,获取文件
f = open(yamlPath,'r',encoding='utf-8')
# 读取文件
cont = f.read()
# 加载数据
x = yaml.load(cont)
# 打印数据
print(x)
# 打印读取写入的数据
print(x.get("cookie1"))
#######################################字符串##############################################
#1、字符串默认不使用引号表示
str1: 这是一个字符串
#2、如果字符串之中包含空格或特殊字符,需要放在引号之中。
str2: '内容: *字符串'
#3、单引号和双引号都可以使用,双引号不会对特殊字符转义。
str3: '内容\n字符串'
str4: "content\n string"
#4、单引号之中如果还有单引号,必须连续使用两个单引号转义。
s3: 'labor''s day'
#5、字符串可以写成多行,从第二行开始,必须有一个单空格缩进。换行符会被转为空格
strline: 这是一段
多行
字符串
#6、多行字符串可以使用|保留换行符,也可以使用>折叠换行
this: |
Foo
Bar
that: >
Foo
Bar
#7、+表示保留文字块末尾的换行,-表示删除字符串末尾的换行。
s4: |
Foo4
s5: |+
Foo5
s6: |-
Foo6
s7: |
Foo7
###################################对象####################
#1、对象的一组键值对,使用冒号结构表示。
animal: pets #{'animal': 'pets'}
#
##2、Yaml 也允许另一种写法,将所有键值对写成一个行内对象
dict1: { name: Steve, foo: bar } #{'dict1': {'foo': 'bar', 'name': 'Steve'}}
####################################数组###################
# 1、数组可以采用行内表示法。
animal: [Cat, Dog]
#{'animal': ['Cat', 'Dog']}
#2、一组连词线开头的行,构成一个数组。
animal1:
- Cat
- Dog
- Goldfish
# {'animal1': ['Cat', 'Dog', 'Goldfish']}
############################复合结构##########################
#对象和数组可以结合使用,形成复合结构
languages:
- Ruby
- Perl
- Python
websites:
YAML: yaml.org
Ruby: ruby-lang.org
Python: python.org
Perl: use.perl.org
#{'languages': ['Ruby', 'Perl', 'Python'], 'websites': {'Python': 'python.org', 'YAML': 'yaml.org', 'Ruby': 'ruby-lang.org', 'Perl': 'use.perl.org'}}
db:
host: xxx
port: 3306
user: weibospider
password: xxx
db_name: weibo
db_type: mysql
#{'db': {'host': 'xxx', 'db_name': 'weibo', 'user': 'weibospider', 'db_type': 'mysql', 'password': 'xxx', 'port': 3306}}
##########################纯量#############################
#1、数值直接以字面量的形式表示
number: 12.30 #{'number': 12.3}
#2、布尔值用true和false表示
isSet: true #{'isSet': True}
isSet1: false #{'isSet1': False}
3、null用~表示
parent: ~ #{'parent': None}
#4、时间采用 ISO8601 格式。
time1: 2001-12-14t21:59:43.10-05:00 #{'time1': datetime.datetime(2001, 12, 15, 2, 59, 43, 100000)}
##5、日期采用复合 iso8601 格式的年、月、日表示。
date: 2017-07-31 #{'date': datetime.date(2017, 7, 31)}
#6、YAML 允许使用两个感叹号,强制转换数据类型。
int_to_str: !!str 123 #{'bool_to_str': 'true'}
bool_to_str: !!str true #{'bool_to_str': 'true'}